Python Object Comparison : “is” vs “==”
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") |
chevron_right
filter_none
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") |
chevron_right
filter_none
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") |
chevron_right
filter_none
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).
Recommended Posts:
- Python | Excel File Comparison
- Chaining comparison operators in Python
- Object Oriented Programming in Python | Set 2 (Data Hiding and Object Printing)
- Python | Data Comparison and Selection in Pandas
- Object Oriented Programming in Python | Set 1 (Class, Object and Members)
- Python | Tkinter ttk.Checkbutton and comparison with simple Checkbutton
- Python | os.confstr_names object
- Python | os.sysconf_names object
- Python | os.supports_dir_fd object
- Python | os.environ object
- Python | os.supports_fd object
- Python | object() method
- Python | os.supports_bytes_environ object
- Python | os.supports_bytes_environ object
- Python | os.supports_follow_symlinks object
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



