tuple
Python's tuple is similar to a list, except that the elements of the tuple cannot be modified . The tuple uses parentheses, and the list uses square brackets. After the tuple is declared, the length is fixed.
In [1]: my_strs=("a","bbb",'ccc') In [2]: my_strs Out[2]: ('a', 'bbb', 'ccc') In [3]: my_strs[0] Out[3]: 'a' In [4]: my_strs[-1] Out[4]: 'ccc' In [5]: my_strs[3] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-5-978c5894f0f0> in <module>() ----> 1 my_strs[3] IndexError: tuple index out of range In [6]: my_strs[0]="aaa" --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-6-4152d9453e33> in <module>() ----> 1 my_strs[0]="aaa" TypeError: 'tuple' object does not support item assignment In [ 8]: len(my_strs) #The tuple is defined , and the length is fixed. Out[8]: 3 In [11]: name=[1,2,3,4] In [ 12]: my_tuple=(100,200,name) #The elements in the tuple are lists In [ 13 ]: my_tuple Out[13]: (100, 200, [1, 2, 3, 4]) In [15]: my_tuple[2] Out[15]: [1, 2, 3, 4] In [ 16]: my_tuple[2][0]=100 #If the tuple contains a list, the list itself can be modified. In [ 17 ]: my_tuple Out[17]: (100, 200, [100, 2, 3, 4])
Tuples are not added, deleted, or modified, only the built-in functions index, count, in, not in are searched.
In [17]: my_tuple Out[17]: (100, 200, [100, 2, 3, 4]) In [19]: my_tuple.index(100) Out[19]: 0 In [20]: my_tuple.count(100) Out[20]: 1 In [21]: 100 in my_tuple Out[21]: True In [22]: 100 not in my_tuple Out[22]: False In [23]: