Identity Operators in Python
Everything in python is an object
Python has a built-in function id()
which provides the id of the memory location associated with that particular object
For example
a = 3
b = [12,54,6,9,1]
print(id(a))
print(id(b))
Output
10742600
140311838537856
Now suppose, if we try to assign the same value to two different variables, then the memory manager in python will reuse the object instead of creating another object
For example
a = 3
b = 3
c = a
print(id(a))
print(id(b))
print(id(c))
print(id(3))
Output
10742600
10742600
10742600
10742600
Python provides operators to perform comparisons on these unique ids, known as identity operators in python
Types of Identity Operators
is
is not
is
operators determine whether two objects refer to an identical memory location or not
whereas is not
operator determines whether two objects refers to a distinct memory location or not
For Example
a = 3
b = 3
c = 7
if a is b:
print("a is equal to b and both refers to same memory location :", id(3))
if a is not c:
print("a is no equal to b and both refers to distinct memory locations :", id(a), id(c))
Output
a is equal to b and both refers to same memory location : 10742600
a is no equal to b and both refers to distinct memory locations : 10742600 10742728
Difference between is
and ==
is
operator computes equivalence based on memory location (id) whereas ==
operator computes equivalence based on values
==
will return True
if we compare two objects with same values irrespective of their memory locations
For example
list_1 = [12,3,2,65,9]
list_2 = [12,3,2,65,9]
if list_1 is list_2:
print("is operator returns True")
if list_1 is not list_2:
print("is not operator returns True because list_1 and list_2 compared based on their different memory locations - ", id(list_1), id(list_2))
if list_1 == list_2:
print("== operator returns True because list_1 and list_2 are compared based on their values", list_1, list_2)
Output
is not operator returns True because list_1 and list_2 compared based on their different memory locations - 139674682721152 139674682769856
== operator returns True because list_1 and list_2 are compared based on their values [12, 3, 2, 65, 9] [12, 3, 2, 65, 9]