== is comparing values
In Python, == compares the value of two variables and returns True as long as the values are equal.
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.
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.
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
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
is will be more complicated when we comparing two strings. Generally, strings longer than 20 characters will be interned.
But any string constructed at runtime (produced through methods, functions, etc.) will not be interned.
Which one to use
If you want to compare values, always choose to use
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 helpful insights, It's Free!😋