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?
Getting the size of an integerTo store the number 0, Python uses 24 bytes. Since storing the number zero, Python needs to use only 1 bit. Note that 1 byte equals 8 bits. Therefore, you can think that Python uses 24 bytes as an overhead for storing an integer object.
So the reason why you are seeing an int as 4 bytes (32 bits), is because the code is compiled to be executed efficiently by a 32-bit CPU. If the same code were compiled for a 16-bit CPU the int may be 16 bits, and on a 64-bit CPU it may be 64 bits.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With