The only difference between a tuple and a list is that the list can be changed, but the tuple cannot be changed. Other functions are the same as the list
Two ways to create a tuple
One
ages = (11, 22, 33, 44, 55)
The second
ages = tuple((11, 22, 33, 44, 55))
If there is only one element in the ancestor, then a comma needs to be added, otherwise it will become a string.
In [1]: t = (1) In [2]: t Out[2]: 1 In [3]: type(t) Out[3]: int In [4]: t = (1,) In [5]: t Out[5]: (1,) In [6]: type(t) Out[6]: tuple
View the number of occurrences of elements in the list
count(self, value):
Attribute | Description |
---|---|
value | The value of the element |
>>> ages = tuple((11, 22, 33, 44, 55)) >>> ages (11, 22, 33, 44, 55) >>> ages.count(11) 1
Find the position of the element in the tuple
index(self, value, start=None, stop=None):
Attribute | Description |
---|---|
The value of the element | |
Starting position | |
Ending position |
>>> T = (1,2,3,4,5) >>> (x * 2 for x in T) <generator object <genexpr> at 0x102a3e360> >>> T1 = (x * 2 for x in T) >>> T1 <generator object <genexpr> at 0x102a3e410> >>> for t in T1: print(t) ... 2 4 6 8 10
>>> tup=("tup",["list",{"name":"ansheng"}]) >>> tup ('tup', ['list', {'name': 'ansheng'}]) >>> tup[1] ['list', {'name': 'ansheng'}] >>> tup[1].append("list_a") >>> tup[1] ['list', {'name': 'ansheng'}, 'list_a']
>>> T = (1,2,3) >>> T = T[:2] + (4,) >>> T (1, 2, 4)