The Python identity operators are one of the operator types and checks if variables point to the same object in memory.
What does this mean? It’s best explained with some examples.
Let’s configure two variables with the same string:
Variable “a” is the same as “b”. This makes sense right? Let’s try something else. We create two more variables with the same string:
This looks weird. The two strings are equal, but the IS operator returns False to us. Why?
Everything in Python is an object and objects are stored at a specific memory location. Python is also efficient and uses the same memory location for certain objects. For example, short strings or integers between -5 and 256.
With the id() function, we can check the identity of an object. Let’s check those variables we configured:
Above, you see that variable “a” and “b” refer to the same ID. Variable “c” and “d” however, are different:
Besides the IS operator, you can also use the IS NOT operator. Here is a quick example:
The main reason I’m explaining these two operators is that at first sight, it makes sense to use “is” or “is not” in your code to compare two values. It looks nice and clean.
Looks can be deceiving. These two operators, check if two objects point to the same memory location. They don’t check whether two values are equal or unequal. Long story short, don’t use the IS and IS NOT operators but use the comparison operators instead:
I hope you enjoyed this lesson. If you have any questions, please leave a comment.