In the front there is an increase in tuples tuple is one of the sequence, the elements of a tuple are enclosed in parentheses ():
Tup1 = (1, ' Hello ', ' a ', ' B ', ' C ', 2.01) print (tup1) #使用for循环依次打印tuple中的每一个元素for v in Tup1:print (v) #使用下标访问每一个元素for I In range (len (tup1)): Print (Tup1[i]) >>>1helloabc2.01
The creation of a tuple is as simple as enclosing the element in parentheses () and separating the elements with commas.
A tuple can hold any type of element, except for integers, floating-point numbers, strings, or tuples, lists, and so on, in addition to the code shown above.
Tup2 = (tup1, ' tup2 ') #print (tup2) for V in Tup2:print (v) >>> (1, ' Hello ', ' a ', ' B ', ' C ', 2.01) tup2
The most important feature of the tuple is: after the creation, the element cannot be modified (including delete), the modification will be directly error.
TUP2[1] = ' abc ' Traceback (most recent): File "<pyshell#18>", line 1, <module> tup2[1] = ' abc ' TypeError: ' Tuple ' object does not support item assignment
The access of the tuple element, which has been shown by subscript to access, in fact, can also be intercepted, to get a sub-tuple
Print (tup1[1:]) >>> (' Hello ', ' a ', ' B ', ' C ', 2.01) print (Tup1[1:-1:2]) >>> (' Hello ', ' B ')
Tuple connection, two tuple can be "+", the two tuple is connected to a new tuple
tup3= (' abc ',) #定义只有一个元素的tuple, need to be added in the back ', ' Print (Tup1 + tup3) >>> (1, ' Hello ', ' a ', ' B ', ' C ', 2.01, ' abc ')
Gets the number of tuple elements:
Print (len (tup1))
To convert a list to a tuple:
List1 = [' A ', ' B ', ' C ']tuple (list1) >>> (' A ', ' B ', ' C ')
Getting Started with Python (v) tuple