Full answer
a = [1, 2]; b = a; c = [1, 2]
print(a == c, a is c, a is b)
x, y = 256, int("256")
print(x == y, x is y)
x, y = int("257"), int("257")
print(x == y, x is y)
class AlwaysEqual:
def __eq__(self, other): return True
obj = AlwaysEqual()
print(obj == None, obj is None)Output:
True False True
True True
True False
True FalseTwo separate lists with the same contents are equal but not identical. b = a makes both names refer to one object, so is is True. The integers 256 are the same cached object in CPython, while 257 built at run time with int('257') gives two different objects, so is returns False although the values are equal. Relying on this would make code break on other interpreters or even other contexts.
x is None is the idiomatic check because None is a singleton and the check cannot be fooled by a custom __eq__, as the AlwaysEqual class shows: it claims to equal None with == but is not None.
CPython 3.8+ emits a SyntaxWarning for is with a literal, such as x is 5, which catches many of these mistakes.
a = [1, 2]; b = a; c = [1, 2]
print(a == c, a is c, a is b)
x, y = 256, int("256")
print(x == y, x is y)
x, y = int("257"), int("257")
print(x == y, x is y)
class AlwaysEqual:
def __eq__(self, other): return True
obj = AlwaysEqual()
print(obj == None, obj is None)Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- == compares values
- is compares identity
- Small int caching is an implementation detail
- Use is for None
- Custom __eq__ can fool ==
Common mistakes
- Comparing numbers or strings with is
- Writing x == None
Follow-ups
- What is string interning?
- Why does x is 5 produce a warning?
Tips
- Use is only for singletons