"Variable" tuple
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:
>>> 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 theso-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.
Python creates tuples containing lists