Reputation: 86266
Here is what I am looking at:
In [1]: import sys
In [2]: sys.getsizeof(45)
Out[2]: 24
In [3]: sys.getsizeof([])
Out[3]: 72
In [4]: sys.getsizeof(range(1000))
Out[4]: 8072
I know that int
in Python is growable (can get bigger that 24 bytes) objects that live on the heap, and I see why that object can be quite large, but isn't a list just a collections of such objects? Apparently it is not, what is going on here?
Upvotes: 6
Views: 502
Reputation: 91179
A list
is a collection of pointers to objects, not of the objects themselves. So, assuming a 64-bit system, your list has 8000 bytes of pointers plus 72 bytes of overhead.
Upvotes: 2
Reputation: 184270
The list doesn't contain any integers; it contains pointers to various objects, which happen to be integers and which are stored elsewhere. getsizeof()
tells you the size only of the object you pass to it, not of any additional objects it points to.
Upvotes: 8
Reputation: 122456
This is the size of the object - excluding the objects it contains:
>>> d = range(10)
>>> sys.getsizeof(d)
152
>>> d[0] = 'text'
>>> sys.getsizeof(d)
152
>>> d
['text', 1, 2, 3, 4, 5, 6, 7, 8, 9]
The size of the list with 1000 elements, in your case, is 8072
bytes but each integer object is still 24
bytes. The list object keeps track of these integer objects but they're not included in the size of the list object.
Upvotes: 9