Coder's Cat

Python: Is and ==

2020-03-28

file:img/2020_03_28_the-difference-between-is-and-equal-in-python.org_20200328_234214.png

== 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

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

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)

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

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

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

Which one to use

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

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.

Join my Email List for more insights, It's Free!😋

Tags: Python