0

Python lists are mutable because they store references to their elements, instead of the elements themselves. Which means, the list variable would have a different address than the address of its elements. I verified this using the below piece of code:

Input

a_list = [1, 2, 3]

print(a_list, type(a_list), id(a_list))
for x in range(len(a_list)):
  print(x, type(x), id(x))

Output

[1, 2, 3] <class 'list'> 140125075225856
0 <class 'int'> 140125345710288
1 <class 'int'> 140125345710320
2 <class 'int'> 140125345710352

I read somewhere that tuples are stored in a single block of memory. When I read this, I assumed that a tuple as a whole would occupy a single memory block, which means that, the address of the tuple, as well as those of its elements, would be the same.

However, when I ran a similar piece of code for a tuple, the tuple variable and its elements, all had different addresses as shown below:

Input

a_tuple = (1, 2, 3)

print(a_tuple, type(a_tuple), id(a_tuple))
for x in range(len(a_tuple)):
  print(x, type(x), id(x))

Output

(1, 2, 3) <class 'tuple'> 140124247434368
0 <class 'int'> 140125345710288
1 <class 'int'> 140125345710320
2 <class 'int'> 140125345710352

I probably have understood the concept of memory management in lists and tuples wrong. Can someone please elaborate on how exactly elements are stored in lists and tuples?

Thank you in advance!

  • Thought experiment: imagine you create some object `my_obj`. Then create two tuples `t1 = (1, 2, my_obj)` and `t2 = (3, 4, my_obj)`. Now, you haven't made a copy of `my_obj`, so it's stored in only one place. It can't be "inside" the tuples, because (a) it existed before you created the tuples and (b) it can't be in both of them. – slothrop Jul 08 '23 at 11:33
  • 1
    *"Python lists are mutable because they store references to their elements, instead of the elements themselves."* It's true that Python lists store references to their elements, instead of the elements themselves. But the same is true of tuples. The tuple is immutable, so it can reserve a single block of memory to store all the references (not the elements themselves) contiguously. However, a list is mutable, and importantly, its size can change, so it needs to allocate memory more flexibly. – slothrop Jul 08 '23 at 11:33
  • See also: https://stackoverflow.com/questions/46664007/why-do-tuples-take-less-space-in-memory-than-lists – slothrop Jul 08 '23 at 11:39
  • Thank you so much, @slothrop. You have explained it very clearly. – Kanika Nadar Jul 08 '23 at 17:01

0 Answers0