0

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?

13
  • sys.getsizeof(ls[0]) returns the same as sys.getsizeof(i) - 28. There is no difference in size? Commented Jun 12, 2022 at 23:57
  • I edited the original post a little bit; maybe it clear things up... Commented Jun 12, 2022 at 23:59
  • Is the confusion caused by the size of a list increasing by 8 for each element? That's just the size of the pointer/reference to an object, if you add any arbitrary object to the list the size will increase by 8 each time Commented Jun 13, 2022 at 0:03
  • Exactly; increasing by 8 bytes, but the elements in the list are only 4 bytes. Commented Jun 13, 2022 at 0:05
  • 1
    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 Commented Jun 13, 2022 at 0:08

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.