When running Python 2.5.2
>>> a = 256
>>> b = 256
>>> a is b
True # Of course it's true
>>> 257 is 257
True # If you compare 257 directly, it's true
>>> a = 257
>>> b = 257
>>> a is b
False # Why does it say False?
It runs together.
I tested it to see if it depends on the interpreter version, but in Python 2.3.3, Only 99 to 100 people get this result.
Is Python different in terms of storing small integers and large numbers? I don't know why they're producing such different results.
So how do I compare the two numbers stably?
python int identity operator compare
According to Python Standard Library 5.3
is
compares id()
rather than values.
and Python documentation, 7.2.1, "Plain Integrator Objects"
Python stores integer objects as an array of integer objects up to [-5, 256]
When you create an int in this range, it references an object that has already been created.
That is, in the following Python code:
>>> a = 256
>>> b = 256
>>> id(a)
9987148
>>> id(b)
9987148
>>> a = 257
>>> b = 257
>>> id(a)
11662816
>>> id(b)
11662828
When a
and b
store 256, they refer to objects that already exist up to [-5,256], so the two have the same id, so it is true when compared with is
257 creates a new object because it exceeds the range, so the id of the two is different, and false
is returned when compared with is
.
So when comparing values, use ==
instead of is
.
572 Understanding How to Configure Google API Key
885 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
597 GDB gets version error when attempting to debug with the Presense SDK (IDE)
606 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.