list __size__() result depending on creation method

Viewed 172

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
1 Answers

The sizeof() function in Python doesn't exactly tell us the size of the object. It doesn't return the size of a generator object as Python cannot tell us beforehand how to size a generator is. Still, it returns the internal size for a particular object (in bytes) occupying the memory.

Because you use for loop to create a list it takes more memory if it is a huge data it will take more memory resulting in taking more time that's reason you will see TLE in competitive programming questions.

Related