What is the difference between is and == in Python?
== checks whether two objects have equal values, using __eq__. is checks whether two names point to the very same object in memory, by comparing identity. Use is only for singletons like None.
Explain it simply
Two students in a hostel can each own an identical copy of the same textbook. Ask "are the books the same?" and the answer is yes: same content. Ask "is it the same physical book?" and the answer is no. == asks the first question; is asks the second.
In Python, is compares identity (roughly, id(a) == id(b)), while == calls the __eq__ method and compares values.
Example
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b) # True (same values)
print(a is b) # False (two separate list objects)
print(a is c) # True (c is just another name for a)
result = None
print(result is None) # True: the recommended way to test for NoneBecause None, True and False are singletons (only one of each exists), is is the correct and fastest check for them.
What to say in the interview
"== is value equality and goes through __eq__, so a class can define what equal means. is is identity: both names refer to the same object. I use is for None and other singletons, and == for everything else. I never rely on is for numbers or strings, because whether two equal ints or strings share an object is a CPython implementation detail."
Common mistakes
- Writing
if x is 5:. It may appear to work for small numbers due to caching, but it is wrong, and Python 3.8+ warns about it. - Writing
if x == None:. It works for most types, but a class can override__eq__;is Nonecannot be fooled.