Python (four) tuple tuple

Tuple is another ordered list, which translates to "tuple" in Chinese. A tuple is very similar to a list, however, once a tuple is created, it cannot be modified.

t = ('Adam', 'Lisa', 'Bart')

t cannot be changed, tuple has no append() method, nor insert() and pop() methods. Therefore, new students can't directly add to the tuple, and old students can't even quit the tuple. The method of obtaining tuple elements is exactly the same as that of list. We can normally use t[0], t[-1] and other indexing methods to access elements, but cannot be assigned to other elements

t=()
print(t)

result:()

t=(1)
print(t)

Result: 1

Why the number 1?

Because () can not only represent tuple, but also can be used as parentheses to represent the priority of the operation, the result (1) is calculated by the Python interpreter as the result 1, so we get not a tuple, but an integer 1.
It is precisely because of the ambiguity of using () to define a single-element tuple, so Python stipulates that a single-element tuple should be added with a comma ",", which avoids the ambiguity:

t=(1,)
print(t)

Output: (1,)

"mutable" tuples

t = ('a', 'b', ['A', 'B'])
L=t[2]
L[0]='x'
L[1]='y'
print(t)

Output:
('a', 'b', ['x', 'y'])
write picture description here
When we change the elements 'A' and 'B' of the list to 'X' and 'Y', the tuple becomes:
write picture description here

On the surface, the elements of the tuple have indeed changed, but in fact, it is not the elements of the tuple that have changed, but the elements of the list.

The list pointed to by the tuple at the beginning has not been changed to another list, so the so-called "unchanged" of the tuple means that each element of the tuple points to the same forever. That is, if it points to 'a', it cannot be changed to point to 'b', and if it points to a list, it cannot be changed to point to other objects, but the pointed list itself is variable!

After understanding "pointing to the same", how to create a tuple with the same content? Then it must be ensured that each element of the tuple itself cannot be changed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325733648&siteId=291194637