Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is single int 24 bytes, but in list it tends to 8 bytes

Tags:

python

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?

like image 229
Akavall Avatar asked Jun 19 '15 20:06

Akavall


People also ask

Why are Python ints 24 bytes?

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.

Why int is 2 or 4 bytes?

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.


1 Answers

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.

like image 83
Simeon Visser Avatar answered Sep 30 '22 02:09

Simeon Visser