Topic 10 of 58
is vs ==
Overview
The difference between is and == is one of the most common traps in Python coding interviews. The double equals == checks for VALUE equality—do these two variables contain the same data? The is operator checks for IDENTITY—do these two variables point to the exact same physical memory address? Understanding this is critical for avoiding subtle bugs with mutable objects.
Syntax
python
list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_c = list_a
# Value Equality
print(list_a == list_b) # True (They contain the exact same data)
# Identity Equality
print(list_a is list_b) # False (They are two separate objects in memory)
print(list_a is list_c) # True (They point to the exact same memory address)
# Checking for singletons
user = None
print(user is None) # True (The correct, Pythonic way to check for None)Common Pitfalls
- Using
isto compare strings or integers. Because Python optimizes memory by caching small numbers and short strings (interning),ismight sometimes return True for equal values, but it is highly unpredictable and unsafe. - Using
if var == None:. You should ALWAYS useif var is None:because there is only oneNoneobject globally, and malicious classes can override==to trick you.
Interview Questions
Q:
Why does
a = 256; b = 256; print(a is b) return True, but a = 257; b = 257; print(a is b) returns False?A:
This happens due to Integer Interning. Python pre-allocates memory for small integers from -5 to 256 to save memory. Any variables assigned these values point to the same cached objects. Numbers outside this range get distinct memory addresses.
Real-World Example
Safely instantiating mutable default arguments inside a function.
example
python
def add_item(item, target_list=None):
# Using 'is None' is the safest, most performant way to check
# if the caller omitted the target_list argument.
if target_list is None:
target_list = []
target_list.append(item)
return target_listCheck Your Knowledge
Test your understanding of is vs == with these quick questions.