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: