5

I have the list created in 3 different ways and the __sizeof__() 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
Kelly Bundy
  • 23,480
  • 7
  • 29
  • 65
  • 1
    Does this answer your question? [Python generator objects: \_\_sizeof\_\_()](https://stackoverflow.com/questions/12477835/python-generator-objects-sizeof) – AmilaMGunawardana Feb 26 '22 at 09:10
  • 1
    The proposed duplicate is not appropriate. This effect is from overallocating and trimming lists, since they must be prepared to change size. The dupe is about confusing size with length. – MisterMiyagi Feb 26 '22 at 09:20
  • [Another similar question](https://stackoverflow.com/q/60549865/12671057), showing overallocations at different sizes – Kelly Bundy Feb 27 '22 at 11:56
  • `__sizeof__` is an implementation detail of CPython, not part of the language. Unless you are hacking on CPython itself, you shouldn't care what it returns (or even if it is available.) – chepner Feb 27 '22 at 15:31

0 Answers0