backend / python core / 21_is_equal.md

Python, Backend, and Architecture Learning Notes

3 interview angles 2 min read source

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 True if 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 True if 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 is when you want to check object identity (e.g., if a variable is None).
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 returns NotImplemented, Python tries the reflected operation on the right. Returning NotImplemented rather than False is 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=True generates __eq__ from the fields; frozen=True additionally generates __hash__. That’s the least error-prone way to get both right.