Search code examples
pythonmemorydata-structures32bit-64bit

Python 32 bit int, but 64 bit when int in array


Python 3.8.10; Linux Ubuntu

If the integer 5 is referenced in the same memory address for both the integer i and the 1st position in ls list variable, why does the stand alone integer suggest 32 bits, while the same integer in the list (with the same memory address) show as 64 bit?

The confusion comes from the fact that an empty list has an overhead of 56 bytes on my machine.

import sys

# 32 bit integers
l = int()
sys.getsizeof(l)  # 24 bytes overhead; 144 bits
i = 5
hex(id(i))  # 0x955ea0
sys.getsizeof(i)  # 28 bytes; 24 bytes of overhead; 4 bytes (32 bits)

ls = []
sys.getsizeof(ls)  # 56 bytes

ls = [5]
hex(id(ls))  # 0x7f7c400ca500
hex(id(ls[0]))  # 0x955ea0

64 bytes for a list with 56 bytes overhead and one integer element...

This suggests an 8 byte, 64 bit integer (below):

sys.getsizeof(ls)  # 64 bytes; 56 bytes overhead; 8 bytes for single integer; 64 bit integer

However, element does point to a memory address of a 32-bit integer...

sys.getsizeof(ls[0])  # 28 bytes; 24 bytes overhead; 4 bytes for single integer; 32 bit integer

What are the mysterious 4 bytes?

IS IT THE ADDITIONAL SPACE ALLOCATED IN AN ARRAY FOR AN ADDITIONAL INTEGER?


Solution

  • The value returned when calling sys.getsizeof on a list does not include the size of the elements in the list, the 8 bytes are just the size of the pointer/reference to each element – Iain Shelvington