-2

I have a simple code I stumbled upon on HyperSkill and was testing it on the Python console, both Python2 and Python3. The results confused me.

>>> a = 5
>>> b = 5
>>> a == b
True
>>> a is b
True
>>> x = 1000
>>> y = 1000
>>> x == y
True
>>> x is y
False
>>>

I don't understand why the result of a is b is True and yet the result of x is y is (as expected) False

  • @DeepSpace Another answer worth examining: [Is there a difference between “==” and “is”?](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is) – Tom Karzes May 18 '19 at 00:03
  • Or this.. [“is” operator behaves unexpectedly with integers](https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers) @DeepSpace, thanks! – Christopher Chaduka May 19 '19 at 11:59

1 Answers1

0

The is operator compares whether two objects are assigned to the same underlying object in memory. The == operator compares whether two objects have the equivalent value.

Small integer values (-5 to 256) are stored in memory in Python for efficiency. Assigning a variable to be one of those value integers will always assign it to the same underlying object in Python's memory. For larger values, a new object is created.

Here is some code to show it:

for x, y in zip(range(-7,260), range(-7,260)):
    print(x, x is y)

# prints:
-7 False
-6 False
-5 True
-4 True
-3 True
-2 True
-1 True
0 True
1 True
2 True
... 
254 True
255 True
256 True
257 False
258 False
259 False
James
  • 32,991
  • 4
  • 47
  • 70