The difference between ‘==’ and ‘is’ in Python

The Equality operator (==) compares the values of operands on either side and checks for value equality. Whereas the ‘is’ is an identity keyword that checks whether both the operands refer to the same object in memory or not.

Suppose, if we take two variables a and b with the same value. Now as we already know, in python, variables with equal values are assigned the same id for their objects to save the memory. So, is keyword when used with a and b returns True.

Python ‘==’ and ‘is’ Examples:

Example 1: In this example, we will demonstrate the working of == and is using the list.

#Initializing
l1=[2,4,6,8]
l2=[2,4,6,8]
l3=l1
#Checking for equality
print("l1==l3 is ",l1==l3)
print("l1==l2 is ",l1==l2)
print("l1 is l3 - ",l1 is l3)
print("l1 is l2 - ",l1 is l2)

Output

l1==l3 is  True
l1==l2 is  True
l1 is l3 -  True
l1 is l2 -  False

Example 2: In this case, we will initialize two variables with the same value and demonstrate the working of is and == in Python.

#Initializing 
a=c=10
print("Before updating value of a")
print(id(a))
print(id(c))
print("a==c - ", a==c)
print("a is c - ",a is c)
#updating value of a
a=a+30
print("After updating value of a")
print(id(a))
print(id(c))
print("a==c - ", a==c)
print("a is c - ",a is c)

Output

Before updating value of a
140155144701504
140155144701504
a==c -  True
a is c -  True
After updating value of a
140155144702464
140155144701504
a==c -  False
a is c -  False

Example 3: In this example, We will take two different strings and then update them with the same value as the first one.

#Initializing 
a="Python"
c="Python Programming"
print("Before updating value of c")
print(id(a))
print(id(c))
print("a==c - ", a==c)
print("a is c - ",a is c)
#updating value of c
c="Python"
print("After updating value of c")
print(id(a))
print(id(c))
print("a==c - ", a==c)
print("a is c - ",a is c)

Output

Before updating value of c
139721358837168
139721358108992
a==c -  False
a is c -  False
After updating value of c
139721358837168
139721358837168
a==c -  True
a is c -  True

References

Happy Learning 🙂

Leave A Comment