Running interpreter
>>> x = 5000
>>> y = 5000
>>> print(x is y)
False
running the same in script using python test.py
returns True
What the heck?
Running interpreter
>>> x = 5000
>>> y = 5000
>>> print(x is y)
False
running the same in script using python test.py
returns True
What the heck?
The is
operator only returns True
when the two operands reference the exact same object. Whether the interpreter chooses to create new values or re-use existing ones is an implementation detail. CPython (the most commonly used implementation) is clearly quite happy having several different integer objects that will compare equal, but not identical.
Similarly there are no guarantees that the interpreter's behaviour will be the same as far as memory allocation and value creation are concerned. When running interactively quite a lot happens between the execution of successive statements. Running non-interactively none of that stuff (bind value of the expression to the _
variable, print out the value followed by a prompt, etc.) needs to happen, and so it's easier for the interpreter to re-use a just-created value.
Python allocates some numbers at start.
for x,y in zip(range(256,258),range(256,258)):
print(x is y)
x=y=5000
print(x is y)
This will print on my machine:
True
False
True
The first print is True because it was in the allocated range and both x and y refer to the same number. The False indicates that both x and y will create an integer object and these won't be the same. The last one is True because I specifically told Python to make x and y the same object.
If you want to check equality, use ==
instead of is
.