How allocation of memory for `list` works in Python? Why size of list is not same as combined sum of its objects?

Viewed 86

I have below program to print the id and size of list and it's elements.

import sys

a=[1,2,3]

print(id(a))
print(id(a[0]))
print(id(a[1]))
print(id(a[2]))

print("=================")

print(sys.getsizeof(a))
print(sys.getsizeof(a[0]))
print(sys.getsizeof(a[1]))
print(sys.getsizeof(a[2]))

which prints:

139954746492104
10914496
10914528
10914560
=================
88
28
28
28

Few Questions:

  • The size of a[0] is 28. When I multiply 28*3=84, how size of list a is 88?
  • When I subtract address of a[1] - a[0] i.e. 10914528 -10914496 = 32 How I am getting 28 when I use size of function?
  • id of a is 139954746492104. Then how id of a[0] is 10914496?
2 Answers

Lists in python doesn't contain the object itself. They just store the reference to the object. Hence, the size of object at any index is not proportional to size of the list. For example:

>>> import sys
>>> my_list = [10, "my_str", {}]


>>> sys.getsizeof(my_list[0])  # it is memory used by int
24
>>> sys.getsizeof(my_list[1])  # it is memory used by str
43
>>> sys.getsizeof(my_list[2])  # it is memory used by dict
280

>>> sys.getsizeof(my_list)  # and it is memory used by your list object itself
96

Here, size of my_list is 96 Bytes, whereas my_list[2] alone is 280 Bytes.


Answering your questions:

The size of a[0] is 28. When I multiply 28*3=84, how size of list a is 88?

As I mentioned above, list just holds the reference to objects, not the objects itself. Hence the memory used by list and memory used by each of it's objects are not going to be same.

When I subtract address of a[1] - a[0] i.e. 10914528 -10914496 = 32 How I am getting 28 when I use size of function?

a[1] and a[0] refer two independent objects, memory allocation of which is not guaranteed to be contagious.

id of a is 139954746492104. Then how id of a[0] is 10914496?

Same as above. Because both display two independent objects.

The list itself without any elements already have some size, not only the values.

Related