We can compare 2 variables with is
and ==
in Python:
>>> a = None
>>> b = None
>>> a is b
True
>>> a == b
True
But what's the difference between these two?
The short answer is: is
compares two variable's ID, and ==
compares their value.
Let's see an integer example:
>>> a = 2
>>> b = 2
>>> a is b
True
>>> a == b
True
>>> id(a)
4343713584
>>> id(b)
4343713584
We can see a
and b
's value are equal, and because their ID are the same, so is
returns True too.
Let's see another example which is
returns "False":
>>> a = 257
>>> b = 257
>>> a is b
False
>>> a == b
True
>>> id(a)
4347529424
>>> id(b)
4347529360
Let both a
and b
to be 257, we can see their values are equal, but is
returns False.
Let's try 256:
>>> a = 256
>>> b = 256
>>> a is b
True
>>> a == b
True
>>> id(a)
4343721712
>>> id(b)
4343721712
Wait, if we use 256, both is
and ==
returns True, because their ID and value are the same. But if we just increase one to 257, is
will return False, so what happened here? Is 257 a special number in Python?
The answer is, to save some speed, Python put some small integers inside a pool. We all have the experience like using a loop to increase an integer from 1 to 10, since those small integers are frequently used, Python will create them once, and if there is another variable trying to use it, Python won't create a new one, it will just give this variable a reference to that number which is already created in the pool.
By default, Python put integers between [-5, 257) to that small integer pool, if you are interested, you can check CPython's source code here.
So this explained why is
and ==
both returned True for 256. But for 257, Python will created two separated integer object to a
and b
, thus, their ID are different.
We can verify this with -5 and -6 too:
>>> a = -5
>>> b = -5
>>> a is b
True
>>> a = -6
>>> b = -6
>>> a is b
False
Top comments (0)