0

I understand since tuples are immutable, they are typically stored in contiguous memory blocks for efficiency. But I would like to understand how tuples are stored when elements are mutable e.g. list.

Concretely, I can create a tuple with a list as element and then add to this list. How is tuple stored in memory in this case? Is it just storing reference? If so, how does it decide to store reference vs value?

t = (1,2,[])
t[2].append(3)
print(t)
# (1, 2, [3])
Mechanic Pig
  • 6,756
  • 3
  • 10
  • 31
  • 3
    Python (the language) does not define how tuples are stored. These lower levels are abstracted away from the programmer intentionally and a matter of the interpreter. You can still have a look at the source code of the CPython interpreter or any other Python interpreter. – Klaus D. Oct 18 '22 at 03:48
  • Tuples and lists are both stored in contiguous memory blocks, the difference is in the amount of space allocated for them. Neither representation stores the actual primitive data within the structure, they are all pointers because everything in python is an object – Alexander Oct 18 '22 at 03:51
  • 2
    A tuple (or a list) just contains a set of object references. EVERYTHING in Python is an object reference. The tuple really has no idea what is inside it. Could be integer objects, could be list objects, could be other tuple objects. You can manipulate those objects, but that doesn't change the object reference, so the tuple itself is unchanged. – Tim Roberts Oct 18 '22 at 03:52

0 Answers0