1. Preface
A python tuple (tuple) is similar to a list, except that tuples cannot be modified, that is, once a tuple is created, you cannot add new elements to a tuple, you cannot delete elements in an element, and you cannot modify elements in tuples. But tuples can access any element that can be sliced and iterate through, and tuples can be understood as a read-only list.
2. Creation of tuples
Tuple creation is simple, tuples use parentheses, just add elements in parentheses and separate them with commas.
tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')print(tup)#输出('hello', 'world', 'china', 'dog', 'cat')
3. Accessing elements in a tuple in an indexed manner
tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')print(tup[0])print(tup[1])print(tup[2])#输出'hello''world''china'
Access in slices (package left without packet right)
tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')print(tup[0:3]) #打印索引从0到3的元素,不包含索引为3的元素print(tup[1:]) #打印索引从1开始,一直到列表结束所有元素print(tup[:-1]) #打印索引从0到倒数第2个元素之间的所有元素#输出('hello', 'world', 'china')('world', 'china', 'dog', 'cat')('hello', 'world', 'china', 'dog')
4. Delete a tuple
tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')del tupprint(tup)#输出报错,因为元组已经被删除Traceback (most recent call last): File "<stdin>", line 1, in <module>NameError: name 'tup' is not defined
5. Meta-Group traversal
tup = ('hello' , 'world' , 'china' , 'dog' , 'cat')for tt in tup: print(tt)#输出'hello''world''china''dog''cat'
"Fifth" in Python learning: tuples in Python and the methods they have