2 Types of Identity Operators in Python 3

2 Types of Identity Operators in Python 3

Identity operators in Python are used to verify whether two variables refer to same memory location or not.

They are of two types:

Operator Description Example
is It returns true if two variables refer to same memory location. a=10
b=10
print(a is b)Output is True as id(a) is same as id(b) as they both refer to same value 10.
is not It returns true if two variables don’t refer to  same memory location. a=10
b=10
print(a is not b)
 

Output is False as id(a) is same as id(b). Output will be True only if a and b both contain different values.

Program to demonstrate Identity Operators

Output

a=10
b=10
print(a is b)
print(a is not b)
True
False

Examples:

A=10

B=10

A is B      will return True because both A and B are referencing memory address of value 10

We can use id() function to confirm that they both are referencing same memory address.

In[1]: a=10

In[2]: id(a)

Out[2]: 1397613472

In[3]: b=20

Out[3]: 1397613632

In[4]: c=10

Out[4]: 1397613472

In[5]: a is b

Out[5]: false

#Output is False because ids of a1=10 and b=20 are different

In[6]:a is c

Out[6]:True

#Output is True because ids of a1=10 and c=10 are same .

Spread the love
Lesson tags: 2 Types of Identity Operators in Python 3, Identity Operators in Python, is not operator in python, is operator in python
Back to: Python Programming Tutorial
Spread the love