Search code examples
pythonpython-3.xin-memoryempty-list

Python - In-memory size of nested empty lists


The size in memory of an object can be gotten with sys.getsizeof.

As one could expect, the size of [] is smaller than the size of [[]]. On my machine, I get the following sizes:

>>> sys.getsizeof([])
36
>>> sys.getsizeof([[]])
40

Now, whatever the number of nested empty lists I have, I always get the same size:

>>> sys.getsizeof([[[]]])
40
>>> sys.getsizeof([[[[]]]])
40

What is the reason why the size of nested empty lists seems to have an upper boundary?


Solution

  • Reading the documentation would have taught me that when calling getsizeof,

    Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

    Since [] is a container, its size, according to getsizeof, is its own size plus the size of the references it contains, but not the sizes of the objects referred to.

    Therefore, if [] has a size of 36, and a reference has a size of 4, then the size of [[]] is 36+4, hence 40.

    Now, [[[]]] is nothing more than [x] where x is a reference to [[]]. Hence, the size of [[[]]] is the size of [] plus the size of a reference, so 40 as well.