Python, Backend, and Architecture Learning Notes
Difference Between is and == in Python
In Python, is and == are used for comparison, but they serve different purposes:
== (Equality Operator)
- Compares the values of two objects.
- Returns
Trueif the contents of the objects are equal.
x = [1, 2, 3]
y = [1, 2, 3]
print(x == y) # True (values are the same)
is (Identity Operator)
- Checks whether two variables refer to the same object in memory.
- Returns
Trueif they point to the same object.
x = [1, 2, 3]
y = [1, 2, 3]
print(x is y) # False (different objects in memory)
z = x
print(x is z) # True (same object reference)
Practical Differences
- Use
==when you want to compare data (like two lists with the same values). - Use
iswhen you want to check object identity (e.g., if a variable isNone).
value = None
if value is None:
print("Value is None")
Special Case: Small Integers & Interning
Python interns small integers and strings:
a = 256
b = 256
print(a is b) # True (same interned object)
x = 1000
y = 1000
print(x is y) # False (not interned)
Summary:
| Comparison | Meaning | Checks |
|---|---|---|
== |
Equality of values | Do values match? |
is |
Identity (same object?) | Same memory object? |
Let me know if you want to dive into object interning or memory management next!
Interview angle
- “How does
==actually resolve?” - it calls__eq__on the left operand; if that returnsNotImplemented, Python tries the reflected operation on the right. ReturningNotImplementedrather thanFalseis what lets the other type get a chance. - “What do you need alongside
__eq__?” -__hash__, consistent with it, if instances go in sets or dicts. Defining__eq__alone makes the class unhashable. - “How does a dataclass handle this?” -
eq=Truegenerates__eq__from the fields;frozen=Trueadditionally generates__hash__. That’s the least error-prone way to get both right.