Python's tuples are similar to lists and can be accessed through an index, supporting heterogeneous, arbitrary nesting. The difference is that elements of the tuple cannot be modified. Tuples use parentheses, and the list uses square brackets.
Creating tuples
Tuple creation is simple, just add elements in parentheses and separate them with commas.
Tup1 = () #空元组
Tup2 = (' A ', ' B ', ' C ', ' d ')
Tup3 = (the "A ', ' B ', ' C ')
Tuple operation method and example display
You can use the Dir (tuple) to view the operations supported by tuples
Count
1 function: The number of elements in a statistical tuple 2 return Number of occurrences of value 3 T = ('a','b','c' ,'d', 1,2,2,3,4)4 t.count (2)5 Results: 2
Index
1 function: Gets the index value of the element in the tuple, for the duplicate element, by default gets the index value of the first element from left to 2 syntax: T.index (value, [Start, [stop]])--integer--returnFirst index of value. Raises valueerrorifThe value is notpresent.3 T= ('a','b', 2,'C','D', 1,2,3,4) 4 T.index (2) 5 results:2#element 2 appears for the first time in the position of index 26 T.index (2,3,7) 7 results:6
T1 + T2
1 function: Merge two tuples, return a new tuple, the primitive group is unchanged2Syntax: T = T1 +T23T1 = ('a','b','C')4T2 = (1,2,3,4)5t = T1 + t 26Results:
7 PrintT8('a','b','C', 1,2,3,4)9 PrintT1Ten('a','b','C') One PrintT2 A(1,2,3,4)
T1 * N
1 function: Repeat output tuple n times, return a new tuple, the primitive group is unchanged2Syntax: T = T1 *N3T1 = ('a','b', the)4T = T1 * 35 Results:6 PrintT7('a','b', A.'a','b', A.'a','b', the)8 PrintT19('a','b',----)
Tuples are immutable, but when mutable elements are nested in a tuple, the mutable element is modifiable, the tuple itself is unchanged, and is viewed using the ID (tuple).
1T = ('a','b','C', [1,2,3,4],1,2,3)
2 ID (T)
3 1400735104827844 PrintT[3] 5[1,2,3,4] 6T[3].append (5) 7 PrintT[3] 8[1,2,3,4,5] 9 PrintT10('a','b','C', [1,2,3,4,5],1,2,3]
ID (T)
12 140073510482784
Tuples Support slicing operations
1 syntax: T[start [, stop[, step] ]2 Example Demo:3T = ('a','b','C','D','e','F','g','h')4 Printt[:]#Take all elements5('a','b','C','D','e','F','g','h')6 PrintT[2:]#take the element starting at index 2 to the end7('C','D','e','F','g','h')8 PrintT[2:6]#Take index 2 to 6 of all elements, not including index 69('C','D','e','F')Ten PrintT[2:6:2]#from index 2 to 6, take one from every other element One('C','e')
Python sequence tuple (tuple)