'==' and 'is' are comparison operators that serve different purposes. '==' checks whether two objects have equal values, while 'is' checks whether two variables reference the same object in memory. Two objects can contain identical values without sharing the same memory location, making it important to choose the appropriate operator for each comparison.
a = [1,2,3]
b = [1,2,3]
print(a == b)
print(a is b)
Output
True False
Explanation: a and b are separate list objects with identical values [1, 2, 3]. == checks value equality and returns True, while is checks memory identity and returns False.
Using the 'is' operator
The 'is' operator checks if two variables refer to the same object in memory, rather than just having equal values. It returns True only if both variables point to the exact same object in memory.
Example:
x = [10, 20, 30]
# y points to the same memory location as x
y = x
print(x is y)
Output
True
Explanation:
- y is assigned x, meaning both x and y now reference the same object in memory.
- x is y returns True because x and y share the same identity.
Using the '==' Operator
The '==' operator checks if two objects contain the same values, regardless of whether they are stored in the same memory location.
Example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # same values
Output
True
Explanation:
- a and b are both lists containing [1, 2, 3], but they are separate objects in memory.
- a == b returns True because their values are the same.
is vs == Summary Table
| Feature | == | is |
|---|---|---|
| Compares | Values | Object identity |
Returns True when | Values are equal | Both variables reference the same object |
| Checks memory location | No | Yes |
| Common use | Comparing data | Comparing with None or shared references |