Today we’ll be talking about the two identity operators, is and is not.
Here’s the video version of this article:
We use the built-in function id to check the identity of an object. The identities of two objects are different if they have different memory locations.
There are two identity operators which we can use to compare the memory locations of two objects:
is | evaluates to True if the two objects have the same identity, which means we have two references to the same object |
is not | evaluates to True if the two objects have different identities, which means we have two distinct objects |
Here’s how it works. We have two variables referring to the same number 5:
>>> a = 5
>>> b = 5
Turns out a and b refer to the same object:
>>> a is b
True
>>> a is not b
False
Let’s check it out. Indeed, the same identities:
>>> id(a)
1595892064
>>> id(b)
1595892064
Another example:
>>> x = "hello"
>>> y = "hi"
x and y refer to different objects:
>>> x is y
False
From now on y refers to the same object as x:
>>> y = x
So, they have the same identity:
>>> x is y
True
Type Checking
You can also use the identity operators to check whether an object is of a specific type:
>>> type(True) is bool
True
>>> type(7) is not float
True
>>> type("hello") is str
True