3

Small code:

import sys

x = True

print(sys.getsizeof(x))

Python 2 output:

24

Python 3 output:

28

Why does outputs of getsizeof() function different in Python 2 and Python 3?

1
  • 1
    Because the size of True in memory appears to be 4 bytes larger in Python 3. Commented Oct 8, 2018 at 7:47

2 Answers 2

3

For built-in types, sys.getsizeof() returns basically an implementation detail of the Python implementation you are using.

This means that, even for the same Python version, you might see different sizes for different implementations/platforms/builds... Therefore, you cannot rely on specific answers – and much less expect them to stay constant!

Finally, note that sys.getsizeof() is not an operator; it is simply a function of the sys module.

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

Comments

3

On both Python 2 and Python 3, bool is a subclass of int, and True == 1. However, on Python 3, int is the equivalent of Python 2 long, and it stores integers in an arbitrary-precision representation.

On the build of Python 3 you're running, that representation happens to take 4 more bytes to store the value 1 than what the int representation takes on your Python 2 build, most likely due to the ob_size field that stores the length of the arbitrary-precision representation.

If this ever actually matters to a program you write, you're probably doing something really crazy, and/or misusing getsizeof.

1 Comment

You seems to have more clearer answer! Thanks for your comment! :D

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.