The difference
== checks if two values are equal (same content). is checks if two variables point to the same object (same identity).
== (equality)
Checks if values are the same:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True — same values
print(a is b) # False — different objects
is (identity)
Checks if variables point to the same object in memory:
a = [1, 2, 3]
b = a # b points to the same object
print(a is b) # True — same object
print(a == b) # True — also same values
When it matters: None
Always use is (or is not) when checking for None:
value = None
# ✅ Correct:
if value is None:
print("No value")
# ❌ Avoid:
if value == None: # Works but not recommended
print("No value")
When it matters: small integers
Python caches small integers (-5 to 256), so is might work, but don't rely on it:
a = 100
b = 100
print(a is b) # True (cached)
a = 300
b = 300
print(a is b) # False (not cached)
# Always use == for numbers:
print(a == b) # True
Summary
- Use
==: To compare values (numbers, strings, lists, etc.) - Use
is: To check forNone, or when you need to know if two variables point to the same object - Never use
==withNone: Useis Noneoris not None
Common mistake
# ❌ Wrong:
if my_list == []: # Creates a new empty list to compare
print("Empty")
# ✅ Better:
if not my_list: # Checks if list is falsy (empty)
print("Empty")
# Or:
if len(my_list) == 0:
print("Empty")