Python is vs ==: Key Differences Explained

In Python, the fundamental difference between the is and == operators lies in how they compare objects: == evaluates equality of value, whereas is evaluates identity. This article breaks down how each operator works under the hood, demonstrates their behavior with practical examples, and outlines best practices for when to use each in your code.

Equality (==) vs. Identity (is)

The equality operator (==) determines whether the values of two objects are equivalent. When you use ==, Python calls the __eq__() method of the left-hand object to compare its contents with the right-hand object. It does not care where these objects live in memory, only that their data matches.

The identity operator (is) checks whether two variables point to the exact same object in memory. It compares the memory addresses of the operands using Python's built-in id() function. If id(a) == id(b), then a is b evaluates to True.

Code Example: Lists

Collections like lists provide the clearest demonstration of this difference:

list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_c = list_a

# Value comparison
print(list_a == list_b)  # True: both contain identical elements

# Identity comparison
print(list_a is list_b)  # False: they are distinct objects in memory
print(list_a is list_c)  # True: list_c references the exact same list as list_a

Even though list_a and list_b contain the same numbers, they are allocated in separate memory locations. Mutating list_a will not affect list_b, but it will affect list_c.

Python's Object Caching Quirk

With immutable types like small integers (-5 to 256) and short strings, Python uses an optimization technique called interning. Python reuses existing objects in memory rather than creating new ones:

x = 100
y = 100
print(x is y)  # True: Python caches small integers

a = 1000
b = 1000
print(a is b)  # Often False: outside the cached range (behavior depends on Python implementation)

Because interning is an implementation detail of CPython, you should never rely on is to compare values for equality.

Best Practices