Menu

Python's == vs is: the beginner mistake that passes your tests and breaks later
📰

Python's == vs is: the beginner mistake that passes your tests and breaks later

DEV Community: beginners·Fennec Teaches Python·9 days ago
#rgqzfQ1f
#devtobeginners#devto#dev#python#true
Reading 0:00
15s threshold

Fennec Teaches Python

In Python, == and is are two different tests:

  • == asks: do these two objects have the same VALUE?
  • is asks: are these literally the SAME object in memory?
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)   # True  -- same value
print(a is b)   # False -- different objects

Enter fullscreen mode Exit fullscreen mode

Why it fools beginners: CPython caches small integers and short strings, so 256 is 256 can be True while 257 is 257 is False. Your code "works" in the small test and breaks in production.

THE RULE: Use == for values. Reserve is for None, True and False — never for numbers or text.

Fennec Teaches Python makes 60-second videos on Python mistakes like this one. All 18 fixes are collected in the Python Mistakes Pack: https://fennecteachespython.gumroad.com/l/yiokvw