Understanding The Difference Between == And Is Operators In Python

Difference between == and "is" operators in Python

The '==' is called the comparison operator, and 'is' is Identity Operator. The comparison operator checks whether the value of two expressions is equal. But the is operator compares the memory locations of two objects. Small examples are below,

Comparison operator in Python

a=10
b=10
if a == b:
    print("-a is equal to b")
else:
    print(" a is not equal to b")

Output is,

" a is equal to b." 

a=10
b=11
if a == b:
    print("-a is equal to b")
else:
    print(" a is not equal to b")

Output is,

" a is not equal to b" 

Checks whether the values ​​'a' and 'b' compare as given above and returns 'True' if they are equal and 'False' if not.

Identity operator in Python

a=10
b=10
if a is b:
    print(" a=",id(a)," is same to b=",id(b))
else:
    print(" a=",id(a)," is not same to b=",id(b))

output is,

a=140736216888392  is the same to b=140736216888392

a=10
b=20
if a is b:
    print(" a=",id(a)," is same to b=",id(b))
else:
    print(" a=",id(a)," is not same to b=",id(b))

output is,

a= 140736216888392  is not the same to b= 140736216888712

The above example checks whether variables A and B refer to the same object in memory and returns true or false if they do not. The id() function is used to check their memory locations.

Conclusion

In the case of two variables, A=10 and B=10, the "is" operator always refer to the same object in memory. However these are immutable object and they are stored in memory and reused for performance reasons. But mutable objects like list and dictionary use different memory space for the same object. It can be understood by looking at the examples given below:

Examples

a = [1, 2, 3]
b = a
print(a is b)

# True

a = [1, 2, 3]
b = a.copy()
print(a is b)

# False

In this example, both a=[1,2,3] and b=a refer to the same list object, so the output is "true. The same value as a=[1,2,3] is copied to b. Now a and B are both the same list, but B contains the new memory location, so the output is "false".


Recommended Free Ebook
Similar Articles