Tuple (tuple)
Tuple (tuple) is similar to a list, except that the elements of a tuple cannot be modified. Tuples are written in parentheses (()), and the elements are separated by commas.
The elements in a tuple can also be of different types:
#!/usr/bin/python3Tuple= ( ' ABCD ', 786 , 2.23, ' Runoob ', 70.2 )Tinytuple= (123, ' Runoob ')Print (Tuple) # output Full tuplePrint (Tuple[0]) # The first element of an output tuplePrint (Tuple[1:3]) # Output starts from the second element to a third elementprint (tuple[2:]) # Outputs all elements starting from the third element print ( Tinytuple * 2) # output two sub -Group print (tuple + Tinytuple) # Connecting tuples
The result of the above example output:
(' ABCD ', 786, 2.23, ' Runoob ', 70.2)Abcd(786, 2.23)(2.23, ' Runoob ', 70.2 (123, ' Runoob ' , 123, ' Runoob ' ) ( ' ABCD ' , 786 2.23, ' Runoob ' , 70.2, 123, ' Runoob '
Tuples are similar to strings, can be indexed, and subscript indexes start at 0, and 1 is where they start at the end of the list. It is also possible to intercept (see above, not repeat here).
In fact, a string can be thought of as a special tuple.
>>>Tup= (1, 2, 3, 4, 5, 6)>>> Print(Tup[0])1>>> Print(Tup[1:5])(2, 3, 4, 5)>>>Tup[0] = 11 # Modifying tuple element operations is illegalTraceback (mostrecent ): File "<stdin>", line 1 , in <module>TypeError: ' tuple ' Object does not support item Assignment>>>
Although the elements of a tuple cannot be changed, it can contain mutable objects, such as list lists.
Constructing tuples that contain 0 or 1 elements is special, so there are some additional syntax rules:
=() # Empty tuple
=(a) # an element that needs to be added with a comma after the element
String, list, and tuple all belong to sequence (sequence)
Attention:
- 1. As with strings, elements of tuples cannot be modified.
- 2, tuples can also be indexed and sliced, the same way.
- 3. Note the special syntax rules that construct tuples that contain 0 or 1 elements.
- 4, tuples can also use the + operator for stitching.
Tuple (tuples)