DEV Community

Nic
Nic

Posted on • Originally published at coderscat.com on

Python: Is and ==

2020_03_28_the-difference-between-is-and-equal-in-python.org_20200328_234214.png
Figure 1: Photo by Rajiv Perera on Unsplash

== is comparing values

In Python, == compares the value of two variables and returns True as long as the values are equal.

>>> a = "hello cat"
>>> b = "hello cat"
>>> a == b
True

>>> b = "hello dog"
>>> a == b
False
Enter fullscreen mode Exit fullscreen mode

is is comparing object references

is compares the ids of two variables.

That is, the actual comparing is id(a) == id(b), and it will return True only if the two variables point to the same object.

>>> a = "hello cat"
>>> b = a
>>> a is b
True
>>> b is a
True

>>> b = "hello cat"
>>> a is b
False

>>> id(a)
4512387504
>>> id(b)
4512387312
Enter fullscreen mode Exit fullscreen mode

As we can see from the result, even the value of b is still the same with a, the variable of b is bind with a different object. So, a is b will return False.

An Exception for is

According to the above explanation, this code snippet should output False.

a = 2
b = 2
print (a is b)
Enter fullscreen mode Exit fullscreen mode

But in fact, it will output True, because Python has a cache mechanism for small integers. The number between -5 and 256 will be cached. In this case since a and b have the same value, they point to the same object.

Unicode characters decimals 0 to 255 are also initialized when a Python session is started. So

>>> a = chr(80)
>>> a
'P'
>>> b = chr(80)
>>> b
'P'
>>> a is b
True

>>> a = chr(937)
>>> a
'Ω'
>>> b = chr(937)
>>> b
'Ω'
>>> a is b
False
Enter fullscreen mode Exit fullscreen mode

is will be more complicated when we comparing two strings. Generally, strings longer than 20 characters will be interned.

>>> a = "coderscat"
a = "coderscat"
>>> b = "coderscat"
b = "coderscat"
>>> a is b
True
Enter fullscreen mode Exit fullscreen mode

But any string constructed at runtime (produced through methods, functions, etc.) will not be interned.

>>> a = 'coderscat'
>>> b = "".join(['c', 'o', 'd', 'e', 'r', 's', 'c', 'a', 't'])
>>> a is b 
False
>>> a == b 
True
Enter fullscreen mode Exit fullscreen mode

Which one to use

If you want to compare values, always choose to use euqal.

Since the return value of is also depends on the cache strategy in Python, we have limited use-cases for it.

In some scenarios, we need to use is to check whether two variables refer to the same object.

Top comments (0)