← Back to Python, page 1

python-0018 · Easy fresher

How do == and is differ, and why does 'is' sometimes seem to work for numbers and strings?

== compares values by calling __eq__, while is checks whether two names refer to the same object. CPython caches small integers and interns some strings, so is can appear to work for them, but that is an implementation detail. Use is only for singletons such as None, True and False.

Full answer
python
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:

text
True False True
True True
True False
True False

Two 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.

python
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