8

I have the list created in 3 different ways and the __size__() method returns different values for each of them:

>>> l1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print(l1.__sizeof__())
120
>>> l2 = list(i for i in range(10))
>>> print(l2.__sizeof__())
136
>>> l3 = [i for i in range(10)]
>>> print(l3.__sizeof__())
168

Does the way of creation impacts size calculation? My assumpion is that, the data structures should be the same.

Similar test for tuple returns the same size value:

>>> t1 = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
>>> print(t1.__sizeof__())
104
>>>
>>> t2 = tuple(i for i in range(10))
>>> print(t2.__sizeof__())
104
sumixam
  • 96
  • 2
  • 8
    Yes, it depends. List comprehension reallocate list dynamically, generator expression too, but constant list assignment allocates exact size. Tuple is immutable, so it doesn't allocate "extra" memory for future possible elements. Take a look on [this](https://github.com/python/cpython/blob/e86bcfa58080f152f242c756f625f4015671f168/Objects/listobject.c#L61) comment in CPython sources. – Olvin Roght Sep 10 '21 at 16:25
  • Similar question: https://stackoverflow.com/questions/69052936/size-comparison-between-tuple-and-list – Barmar Sep 10 '21 at 16:30
  • @sumixam, answer to your question is [here](https://github.com/python/cpython/blob/e86bcfa58080f152f242c756f625f4015671f168/Objects/listobject.c#L2750). As you see list constructor validates does iterable have length and allocate either exact memory size or call `list_extend()` which allocates some additional space. – Olvin Roght Sep 11 '21 at 13:02
  • @OlvinRoght you probably saved me a few hours. Thx – sumixam Sep 11 '21 at 13:07
  • Also similar: https://stackoverflow.com/a/74086900/13944524 – S.B Dec 31 '22 at 13:36
  • 2
    Does this answer your question? [Why is there a difference in sys.getsizeof for two differently created but equal lists?](https://stackoverflow.com/questions/74086728/why-is-there-a-difference-in-sys-getsizeof-for-two-differently-created-but-equal) – aaron Jan 01 '23 at 03:28

0 Answers0