‘is’ operator
The ‘is’ operator compares the identity of two objects. Here we compare the objects itself.
Example 6:
Python3
x = [ 1 , 2 ] y = [ 1 , 2 ] z = y print ( "x is y : " , x is y) print ( "z is y : " , z is y) print ( "Location of x is " , id (x)) print ( "Location of y is " , id (y)) print ( "Location of z is " , id (z)) |
x is y : False z is y : True Location of x is 139987316430856 Location of y is 139987316430664 Location of z is 139987316430664
In the example above, even if x and y have the same values, they store them in different locations in memory. So it is clear that even though the objects are the same in terms of the values their locations in memory are actually different. We also see that in the above snippet z is y gives True, this is because these objects are actually identical i.e., the location of y and location of z above are exactly the same.
Difference between “__eq__” VS “is” VS “==” in Python
There are various ways using which the objects of any type in Python can be compared. Python has “==” operator, “is” operator, and “__eq__” dunder method for comparing two objects of a class or to customize the comparison. This article explains the above said three operators and how they differ from each other.
Contact Us