Reputation: 34638
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?
Upvotes: 3
Views: 267
Reputation: 26166
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.
Upvotes: 3
Reputation: 281476
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
.
Upvotes: 3