The Wayback Machine - https://web.archive.org/web/20240118181251/https://www.geeksforgeeks.org/python-object-comparison-is-vs/
Open In App
Related Articles

Python Object Comparison : “is” vs “==”

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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).




# Python program to demonstrate working of 
# "=="
  
# Two different objects having same values
x1 = [10, 20, 30]
x2 = [10, 20, 30]
  
# Comparison using "==" operator
if  x1 == x2:
    print("Yes")
else:
    print("No")


Output:

Yes

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.




# Python program to demonstrate working of 
# "is"
  
# Two different objects having same values
x1 = [10, 20, 30]
x2 = [10, 20, 30]
  
# We get "No" here
if  x1 is x2:
    print("Yes")
else:
    print("No")
  
# It creates another reference x3 to same list.
x3 = x1
  
# So we get "Yes" here
if  x1 is x3:
    print("Yes")
else:
    print("No")
  
# "==" would also produce yes anyway
if  x1 == x3:
    print("Yes")
else:
    print("No")


Output:

No
Yes
Yes




x1 = [10, 20, 30]
  
# Here a new list x2 is created using x1
x2 = list(x1)
  
# The "==" operator would produce "Yes"
if  x1 == x2:
    print("Yes")
else:
    print("No")
  
# But "is" operator would produce "No"
if  x1 is x2:
    print("Yes")
else:
    print("No")


Output:

Yes
No


Conclusion:

  • “is” returns True if two variables point to the same object.
  • “==” returns True if two variables have same values(or content).


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated : 10 Sep, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials