Another kind of ordered list is called a tuple: a tuple.

A tuple is very similar to a list, but a tuple cannot be modified once it is initialized.

student = (Students' 2 '.'the bronze mustache case accounted for 3'.'the bronze mustache case accounted for 4'.'the bronze mustache case accounted for 6')
print(student)
print(len(student)) 
Copy the code
(Students' 2 '.'the bronze mustache case accounted for 3'.'the bronze mustache case accounted for 4'.'the bronze mustache case accounted for 6'4)Copy the code

Now, the student tuple can’t change, and it doesn’t have append(), insert(). The other methods of obtaining elements are the same as for list. You can normally use student[0], student[-1], but cannot assign to another element. What’s the point of an immutable tuple? Because tuples are immutable, the code is safer. If possible, use tuples instead of lists.

Tuple’s trap:

  • When you define a tuple, the elements of the tuple must be defined. For example:
t = ('1'.'2'.'3'.'4')
print(t)
Copy the code
('1'.'2'.'3'.'4')
Copy the code
  • To define an empty tuple, write () :
t = ()
print(t)
Copy the code
(a)Copy the code
  • However, to define a tuple with only one element, if you define it this way:
t = (1) 
print(t)
Copy the code
1
Copy the code

I’m not defining a tuple, I’m defining a 1! This is because parentheses () can represent both a tuple and the parentheses in a mathematical formula, which creates an ambiguity, so Python dictates that in this case, the result of the calculation by the parentheses is naturally 1. Therefore, a tuple with only one element must be defined with a comma, to disambiguate:

t = (1,)
print(t)
Copy the code
(1)Copy the code
  • Finally, a “mutable” tuple:
t = ('a'.'b'['A'.'B'])
t[2][0] = 'X'
t[2][1] = 'Y'
print(t)
Copy the code
('a'.'b'['X'.'Y'])
Copy the code

This tuple is defined with three elements: ‘a’, ‘b’, and a list. Once a tuple is defined, it’s immutable. Why did it change then? When we change the elements ‘A’ and ‘B’ of the list to ‘X’ and ‘Y’, the tuple becomes: Ostensibly, the element of the tuple has changed, but it is not the element of the tuple that has changed, but the element of the list that has changed. The original list that a tuple points to doesn’t change to any other list, so by “constant” a tuple means that every element of the tuple points to never changes. If you point to ‘A’, you can’t change it to point to ‘b’. If you point to a list, you can’t change it to point to any other object, but the list that you point to is mutable! Now that I understand “pointing immutable”, how do I create a tuple that also has the same content? You have to make sure that each element of the tuple itself doesn’t change.