How does Python's small integer caching (interning) affect identity comparisons ('is') versus equality comparisons ('==') for integers?
Short answer
CPython pre-caches and reuses integer objects in the range -5 to 256 for performance, so 'is' comparisons between small integers in this range often return True even for separately-created values — but this is an IMPLEMENTATION DETAIL, not a language guarantee, so 'is' should…
Advertisement
AModel answer
CPython pre-caches and reuses integer objects in the range -5 to 256 for performance, so 'is' comparisons between small integers in this range often return True even for separately-created values — but this is an IMPLEMENTATION DETAIL, not a language guarantee, so 'is' should never be relied upon for integer equality; always use '==' for value comparison.
a = 100
b = 100
print(a is b) # True -- likely, due to small int caching (implementation detail!)
c = 1000
d = 1000
print(c is d) # often False -- outside the cached range, separate objects
# Always use '==' for value equality, regardless of caching behavior
print(c == d) # True, reliablyReal-world example
Debugging a subtle bug caused by incorrectly using 'is' instead of '==' to compare integer values.
Likely follow-ups
- Why does CPython specifically choose the range -5 to 256 for this small integer caching optimization?
Related topics