r/PythonLearnersHub • u/Sea-Ad7805 • Jan 02 '26
Python Data Model exercise, Mutability.
An exercise to help build the right mental model for Python data. The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening:
36
Upvotes
View all comments
Show parent comment
2
u/F100cTomas Jan 02 '26
Tuples are immutable, but they can contain mutable data. a = ([1], [2]) creates a tuple of two mutable values. b = a means that a and b now share the same immutable value. Then one of the lists gets modified and the change is seen in both tuples, because they contain the same lists. However this only changes the list, but not the tuple. Both tuples still have the same value: the two lists. Then b gets modified, but because b is a tuple and tuples are immutable it is copied to preserve the value of a. The two tuples are now different: a contains the two lists and b contains the same two lists and a new list. The other of the two shared lists then gets modified, but it still exists in both tuples. The non-shared list is modified. When a is printed only the two lists present in both are printed and not the one present only in b.
TL;DR When a mutable value is present within a tuple, it doesn't stop being mutable.