What is the difference between `is` and `==` in Python?

In Python, `is` and `==` are used for comparison, but they have different functionalities:

1. `is`:
- The `is` keyword is used to test if two variables point to the same object in memory.
- It checks if two variables refer to the same object, not just the same value.
- When `is` is used, it compares the memory address of the objects.
- It returns `True` if the operands refer to the same object, and `False` otherwise.

2. `==`:
- The `==` operator is used to compare the values of two objects.
- It checks if the values of the two operands are equal or not.
- When `==` is used, it compares the values of the objects, not the memory addresses.
- It returns `True` if the values are equal, and `False` otherwise.

Here is an example to illustrate the difference:



list1 = [1, 2, 3]
list2 = [1, 2, 3]

# Using 'is'
print(list1 is list1) # True - Same object
print(list1 is list2) # False - Different objects

# Using '=='
print(list1 == list2) # True - Same values



In the example above, `list1` and `list2` have the same values, but they are stored at different memory locations. `is` returns `False` because they are different objects in memory, while `==` returns `True` because their values are the same.
What is the difference between `is` and `==` in Python?

Related Questions