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!