We saw in the front that the tuple cannot be modified once it is created. Now, let's look at a "mutable" tuple:
>>> t = (' A ', ' B ', [' A ', ' B '])
Notice that T has 3 elements:' A ', ' B ' and a list:[' A ', ' B ']. List as a whole is the 3rd element of a tuple. The list object can be obtained by t[2]:
>>> L = t[2]
Then we change the list's two elements:
>>> l[0] = ' X '
>>> l[1] = ' Y '
Then look at the contents of the tuple:
>>> Print T
(' A ', ' B ', [' X ', ' Y '])
Doesn't it mean that once a tuple is defined, it's immutable? What's the change now?
Don't worry, let's take a look at the definition when the tuple contains 3 elements:
When we modify the list's Elements ' A ' and ' B ' to ' X ' and ' Y ', the tuple becomes:
On the surface, the elements of a tuple do change, but in fact it is not a tuple element, but a list element.
The list that the tuple initially points to is not changed to another list, so the so-called "invariant" of a tuple is that each element of a tuple is directed to never change. That point ' a ', it cannot be changed to point to ' B ', pointing to a list, cannot be changed to point to other objects, but the list itself is variable!
After understanding "point to Invariant", how do you create a tuple that does not change the content? It is important to ensure that each element of a tuple cannot be changed.
Task
A tuple is defined:
t = (' A ', ' B ', [' A ', ' B '])
Because t contains a list element, the contents of the tuple are mutable. Can you modify the above code so that the tuple content is not mutable?
[' A ', ' B '] is a list, so the content is variable, but the content of (' A ', ' B ') is immutable.
Reference code:
t = (' A ', ' B ', (' A ', ' B '))
Print T
Python's "mutable" tuple