Learn Python tuple every day
Learn Python tuple every day
Tuples are a list with restrictions added. The main difference is that once the tuples are determined, they cannot be modified. They can be converted to each other through their constructors.
Advantages
Tuples are very similar to lists, but they have their own advantages:
Tuples are faster than lists, and a string of values are also traversed. tuples are faster than tables to create secure variables, some variables that do not want to be modified after creation can be used as Dictionary keys and set values. The list is changed, and the hash value is uncertain and cannot be created.
You can create an empty tuples using either of the following methods:
t = ()t = tuple()
There are two methods to create a tuples that contain elements. The following operation results are the same:
t = ("a", "b", "c")t = tuple("abc")
Note that the tuple method can have only one parameter at a time, that is, the elements cannot be input as parameters in sequence. It only accepts iteratable objects as its parameters.
Note: When defining tuples that only contain one element with (), add a comma, as shown in figure(2,)
Truncate
The Truncation rules of tuples are the same as those of the list. The returned results are also tuples. For more information, see the list section.
Adding/deleting tuples
The AttributeError error is reported when adding or deleting tuples.
Searching for tuples
The search operation for tuples is the same as that for the list.
Multivariate assignment
I forgot to mention this feature in the list. Python supports the multi-to-many value assignment method, and the left-side brackets can be omitted. However, if the number is not the same, a ValueError error will be thrown:
>>> (x,y,z)=[2,3,4]>>> x2>>> y3>>> z4>>> (x,y,z)=(2,3,4)>>> x2>>> y3>>> x,y=(2,3,4)Traceback (most recent call last): File "", line 1, in
ValueError: too many values to unpack (expected 2)