[Python study notes] list and tuple (tuple)

list和tuple


list

One of the data types built into Python is list.

listIs an ordered collection, you can add and delete elements at any time.

For example, to list Xi'an cuisine, you can use list:

>>> food= ['肉夹馍', '臊子面', '秦镇米皮']
>>> food
['肉夹馍', '臊子面', '秦镇米皮']

This variable foodis just one list.

use Only ()The function can get listthe number of elements:

>>> len(food)
3

index

Can use indexTo access listeach element from index0Start

>>> food[0]
'肉夹馍'
>>> food[1]
'臊子面'
>>> food[2]
'秦镇米皮'
>>> food[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

when indexWhen it exceeds the range, an IndexErrorerror will be reported .

The index of the last element is len(food) - 1.

You can also use -1direct acquisition, and so on -2, -3to obtain

>>> food[-1]
'秦镇米皮'

Modify element

listIs a variable ordered list that can be used append Method to append elements to the end:

>>> food.append('肉丸胡辣汤')
>>> food
['肉夹馍', '臊子面', '秦镇米皮', '肉丸胡辣汤']

You can also insert the specified location, use insert method:

>>> food.insert(1, '甑糕')
>>> food
['肉夹馍', '甑糕', '臊子面', '秦镇米皮', '肉丸胡辣汤']

To delete the element at the specified position, use pop(i) method,

If not fillediThen the default is to delete the last element.

>>> food.pop(1)
'甑糕'
>>> food
['肉夹馍', '甑糕', '臊子面', '秦镇米皮']
>>> food.pop()
'秦镇米皮'
>>> food
['肉夹馍', '甑糕', '臊子面', '秦镇米皮']

An element replace Into another element, it can be directly assigned to the corresponding index position:

>>> food[1] = '镜糕'
>>> classmates
['肉夹馍', '镜糕', '臊子面', '秦镇米皮']

listThe element types in can also be diverse, such as:

>>> L = ['Apple', 123, True]

listThe element can also be another one list:

>>> food = ['剁椒鱼头', '蛋抱混沌', ['番茄焖面', '可乐鸡翅'], '猪肉白菜饺子']
>>> len(food)
4

If you want to get it Cola Chicken Wings Can use food [2] [0]

If listthere is no one element, the length is also 0.


tuple (tuple)

tupleAnd listit is very similar, but tupleonce initialized can not be modified.

>>> food = ('肉末茄子', '菠萝炒饭', '牛腩米粉')

just now,foodThis tuplecannot be changed,

Because it cannot be changed, the code is safer. Use it if possible tuple.

This is also the case.When you define one tuple, the element must be determined.

Small question: how to define a one with only one elementtuple

Is that so?

>>> math = (1)
>>> math
1

No, no, it should be like this:

>>> math = (1,)
>>> math
(1,)

Because parentheses can be expressed as well as parentheses in tuplemathematics

Therefore tuple, you need to add a comma in the definition ,to eliminate ambiguity.

An 'variable tuple(funny emoji)

>>> food = ('黄焖鸡米饭', '蛤蜊蒸蛋', ['拔丝山药', '菠萝咕咾肉'])
>>> food[2][0] = '糖醋排骨'
>>> food[2][1] = '红烧肉'
>>> food
('黄焖鸡米饭', '蛤蜊蒸蛋', ['糖醋排骨', '红烧肉'])
Published 18 original articles · Likes6 · Visits 1859

Guess you like

Origin blog.csdn.net/qq_43479203/article/details/105128513