Identity Operators in Python

In Python, Identity operators are used to compare two variables and check if they refer to same object. If doesn’t matter if the variables hold different or equal values, what matters is if they are actually the same object, with the same memory location.

There are two Identity operators is‘ and ‘is not‘. The ‘is‘ operator returns ‘True‘ if both variables refer to the exact same object in memory, regardless of whether their values are same or different. The ‘is not‘ operator returns ‘True‘ if the variables do not reference the same object.

Let’s write a code in an example below to clearly understand the ‘is‘ and ‘is not‘ identity operators.

x = [1, 2, 3]
y = [1, 2, 3]
z = x

print( x is y ) #Outputs False because x is not the same object as y, irrespective if values of x and y are equal

print (x is z ) #Outputs True, because z is same object as x. 

print (x is not y )  #Outputs True because x is not the same object as y

In an above code we first create two lists with same values, and assign them to ‘x‘ and ‘y‘ variables. Then we declare variable ‘z‘ and assign it to variable ‘x‘, making ‘z‘ the same object as ‘x‘. Then we check if ‘x‘ and ‘y‘ refer to the same object in memory by using print (x is y) function. Since they are separate list objects, it outputs ‘False‘.

Similarly, we use the print( x is z ) function, to check if they refer to the same object. Since ‘x‘ and ‘z‘ point to the same object in memory, so it outputs ‘True‘. At last, we use the print( x is not y ) function to check if ‘x‘ and ‘y‘ do not refer to the same object, as they point to different objects so it outputs ‘True‘. Instead of ‘is not‘ if we have used ‘is‘ operator, it will output ‘False‘.

Identity Operators in Python (with Examples)

Leave a Reply

Your email address will not be published. Required fields are marked *