Python Object Comparison : "is" vs "=="
In Python, both is and == are used for comparison, but they serve different purposes:
- == (Equality Operator) â Compares values of two objects.
- is (Identity Operator) â Compares memory location of two objects.
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.
'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 = x # y points to the same memory location as 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.
== 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
Parameter | == operator | is operator |
---|---|---|
Name | Equality operator | Identity operator |
Functionality | Checks if values of two objects are equal. | Checks if memory addresses of two objects are the same. |
Use Case | Used when we want to compare data stored in objects. | Used when we want to check whether two variables point to the same object in memory. |
Mutable Objects (lists, dicts, sets, etc.) | Returns True if contents are the same, even if they are different objects. | Returns False unless both variables point to the same memory location. |
Immutable Objects (ints, strings, tuples, etc.) | Returns True if values are equal. | May return True due to Python's internal object caching (interning). |
Example 1 | [1,2,3] == [1,2,3] â True | [1,2,3] is [1,2,3] â False |
Example 2 | "hello" == "hello" â True | "hello" is "hello" â True |