I created two separate lists a
and b
with same element in two different ways. Why is there a difference between the size of the two lists?
import sys
a = [0]
print(a)
>>> [0]
print(sys.getsizeof(a))
>>> 72
b = [i for i in range(1)]
print(b)
>>> [0]
print(sys.getsizeof(b))
>>> 96
When the interpreter sees a = [0]
, it knows that it can build a list with just one element.
When it does a list comprehension, it first creates an empty list, then appends items as it goes. It doesn't know beforehand how big the list is going to be, even if it's iterating over something straightforward like range(1)
. So it tries to guess how much memory to allocate, and if it turns out that's not enough, it will have to dynamically increase the memory allocation. That's not cheap, so it may start with a generous guess.