Topic 38 of 64
is, is not
Overview
'is' checks whether two variables point to the exact same object in memory (same id()), unlike == which checks value equality. Mastering this distinction prevents bugs and demonstrates Python internals knowledge in interviews.
Syntax
python
# 'is' — identity check (same object)
x = [1, 2, 3]
y = x
z = [1, 2, 3]
x is y # True (same object)
x is z # False (equal value, different objects)
x == z # True (value equality)
# Correct use: compare to None
result = None
result is None # True (correct idiom)
result == None # works but not idiomaticCommon Pitfalls
- Never use 'is' to compare integers, strings, or other value types — CPython caches small integers (-5 to 256) and interned strings, giving misleading True results.
- PEP 8 says always use 'is' and 'is not' when comparing to None, True, or False.
- Interview tip: id(obj) returns the object's memory address — two objects with the same id() are the same object.
Real-World Example
Safe None checking in a data processing pipeline
example
python
def process(value):
if value is None:
return "missing"
if value is not None and value != "":
return f"Valid: {value}"
return "empty string"
print(process(None)) # missing
print(process("")) # empty string
print(process("hello")) # Valid: hello