Search code examples
pythonsizeofinternals

python sizeof list vs sizeof tuple


I noticed the following fact in python:

>>> (1, 2, 3).__sizeof__()
48

>>> [1, 2, 3].__sizeof__()
64

I understand the difference between list and tuple but I expected their sizeof (size of object in memory) to be the same: both come with methods and both contain same values.

Moreover, the size difference depends on items lenght:

>>> for size in (10, 100, 1000, 10000):
        tuple_ = tuple(range(size))
        list_ = list(range(size))
        print list_.__sizeof__(), tuple_.__sizeof__()     
176   104
984   824
9088  8024
90088 80024
  • How can we explain this ?
  • Where can I find good doc for python internals ?

Solution

  • list objects are designed to grow dynamically (through append, extend or list comprehension building). It wouldn't be performant to perform realloc (and possibly memmove) each time an element is added. So there's a "growth" algorithm which tries to predict how many elements will be needed (that's just a statistical guess of course).

    That's why the actually allocated memory can be greater than the number of items.

    tuple objects are immutable. There's no reason why Python would pre-allocate more elements.

    Some references about list growth algorithm: