Skip to content

Identity operators in Python

  • by

Python Identity operators are used to compare the objects if both the objects are actually of the same data type and share the same memory location.

There are two Identity operators as explained below −

OperatorDescriptionExample
isEvaluates to true if the variables on either side of the operator point to the same object and false otherwise.x is y, here are results in 1 if id(x) equals id(y).
is notEvaluates false if the variables on either side of the operator point to the same object and true otherwise.x is not y, there are no results in 1 if id(x) is not equal to id(y).

Identity operators in Python

Simple example code.

a = 20
b = 20

if a is b:
    print("a and b have same identity")
else:
    print("a and b do not have same identity")

if id(a) == id(b):
    print("a and b have same identity")
else:
    print("a and b do not have same identity")

b = 30
if a is b:
    print("a and b have same identity")
else:
    print("a and b do not have same identity")

if a is not b:
    print("a and b do not have same identity")
else:
    print("Line 4 - a and b have same identity")

Output:

Identity operators in Python

is operator

x = '101'
y = '101'
z = '102'

if x is y:
    print('x is y')
else:
    print('x is not y')
    
if x is z:
    print('x is z')
else:
    print('x is not z')

if y is z:
    print('y is z')
else:
    print('y is not z')

is not Operator

x = '101'
y = '101'
z = '102'

if x is not y:
    print('x is not y')
else:
    print('x not y')

if x is not z:
    print('x is not z')
else:
    print('x is z')

if y is not z:
    print('y is not z')
else:
    print('y is z')

Use the operators to evaluate the following.

QnEquationTrue or False?
1x = 200
y = 500
z = y

print(z is y)
 True  or   False 
2x = 200
y = 500
z = y

print(x is not y)
 True  or   False 

What is the difference between “==” and “is”?

Answer: The is operator will return True if two variables point to the same object, “==” if the objects referred to by the variables are equal.

Do comment if you have any doubts or suggestions on this Python operators topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

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