What is the difference between == and is in Python?
Short answer
== compares values; is compares identity — whether two names point at the exact same object in memory. Use is only with None, True and False.
a = [1, 2, 3]
b = [1, 2, 3]
c = a
a == b # True — same contents
a is b # False — two separate list objects
a is c # True — c is another name for the same list#Why this bites
Small integers and short strings are cached by CPython, so is sometimes appears to work:
x = 256
y = 256
x is y # True — small ints are interned
x = 257
y = 257
x is y # False on most buildsCode that uses is for numbers will pass your tests with small values and fail in production with large ones. This is why linters flag it.
#Where is is correct
if value is None:
...
if flag is True: # rarely needed; usually just `if flag:`None is a singleton — there is exactly one None in a running program — so identity is the right question. It is also faster and cannot be fooled by a class that overrides __eq__.
#Never write == None
if value == None works but is non-idiomatic, and it breaks if the object defines a weird __eq__. is None is the correct form, every time.