Skip to content
Home » Identity operators in Python

Identity operators in Python

Spread the love

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:

isevaluates to True if the two objects have the same identity, which means we have two references to the same object
is notevaluates 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 

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

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 

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

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 

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love

Leave a Reply