as you have already mentioned correctly, Python has both modifiable and non-changeable datatypes. Also correct is that a set is a mutable datatype, while a tuple is a non-changeable datatype. However, this is only true for the first level of a tuple and not for deeper levels, so it is not true for your objects.
Let us illustrate this principle with an example:
t = ([1,1],[2,2])
id(t) # --> 2588744372096
o we have a tuple t
that contains two lists. One could now assume that this tuple could not be changed, because although lists can be changed, tuples cannot. Internally the following happens: The tuple does not directly contain two lists, but in the tuple pointers are stored to the lists. So the element of the tuple at index 0
is a pointer to the list [1,1]
and at position 1
is a pointer to the list [2,2]
. So we can change the list at will without changing the tuple, because it consists only of pointers that do not change. So let's change the first element of the first list:
t[0][0] = 3
print(t) # --> ([3,1],[2,2])
id(t) # --> 2588744372096
As we can see from the same id of the tuple, it is still the same tuple, the contents of the tuple (the pointers) have not changed either.
You can take a look at the website pythontutor.com, which also shows this aspect graphically. The graphical visualization is also available here: Click me. Further information about pointers can be found here: Information about pointers
Best regards
Johannes :)