Python Object Comparison : “is” vs “==”
Last Updated :
10 Sep, 2018
Both “is” and “==” are used for object comparison in Python. The operator “==” compares values of two objects, while “is” checks if two objects are same (In other words two references to same object).
x1 = [ 10 , 20 , 30 ]
x2 = [ 10 , 20 , 30 ]
if x1 = = x2:
print ( "Yes" )
else :
print ( "No" )
|
The “==” operator does not tell us whether x1 and x2 are actually referring to the same object or not. We use “is” for this purpose.
x1 = [ 10 , 20 , 30 ]
x2 = [ 10 , 20 , 30 ]
if x1 is x2:
print ( "Yes" )
else :
print ( "No" )
x3 = x1
if x1 is x3:
print ( "Yes" )
else :
print ( "No" )
if x1 = = x3:
print ( "Yes" )
else :
print ( "No" )
|
x1 = [ 10 , 20 , 30 ]
x2 = list (x1)
if x1 = = x2:
print ( "Yes" )
else :
print ( "No" )
if x1 is x2:
print ( "Yes" )
else :
print ( "No" )
|
Conclusion:
- “is” returns True if two variables point to the same object.
- “==” returns True if two variables have same values(or content).
Share your thoughts in the comments
Please Login to comment...