Python Identity Operator

Identity Operator

Python provides us with two kinds of special operators. These are:

  1. Identity Operator
  2. Membership Operator
  1. Identity Operator: As we already know that everything in Python is an object. The identity operator is used very commonly to check if both the references point to the same object or not, and to do this we use the ‘iskeyword.

Example:

>>>x= 1
>>>y= 1
>>>print(x is y)

Output: True

In the above example, we see that x and y are equal to 1 which means that both of them will be referring to the same object. To check the address of the object we use the ‘is’ special operator also known as the identity operator. This gives a result as True since both of them refer to the same object.

Example:

>>>x= 1
>>>y= 1
>>>print(x is not y)

Output: False

For this example, we see that x and y are equal to 1 which means that both of them will be referring to the same object. Similar to the earlier example we use the ‘is not’ special operator also known as the identity operator to check if the address of both objects is not the same. This gives a result as False since both of them refer to the same object.

Example:

>>>x= 1
>>>y= 2
>>>print(x is y)
>>>print(x is not y)

Output: 

False
True

Similar to the earlier two examples in this one we check the address using the identity operator of two variables i.e. x and y which point to different objects 1 and 2 respectively.

Identity Operators with List:

The ‘is’ operator is not applicable for content comparison and only applicable for address comparison and not for content comparison. 

Example:

lis1= [1, 2, 3]
lis2= [1, 2, 3]
print(id(lis1))
print(id(lis2))
print(lis1 is lis2)

Output:

5666987 #address of list lis1 
5666345 #address of list lis2
False

In the above code, we create 2 lists lis1 and lis2 having same elements 1, 2 and 3. We first print the address of both lists using ‘id’ and then compare Ising ‘is’. In the output, we see that since both the objects are different therefore their addresses are different too and the output is false. 

Note: Here ‘id’ is a predefined function and not a keyword.

Leave a Comment

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