Sobes.tech
Junior — Senior

Analysis of the behavior of the 'is' operator when comparing integers in Python

livecode

Task condition

Explain why the following code produces such results in the Python interactive shell. Pay attention to how Python caches small integers and how this affects object identity checks using the is operator.

>>> x = 256
>>> y = 256
>>> x is y
True

>>> x = 257
>>> y = 257
>>> x is y
False
  • For values from -5 to 256, Python uses an internal cache of small integers, so variables assigned the same value within this range point to the same object in memory – the is check returns True.
  • For numbers outside the cached range (e.g., 257), each assignment creates a new object. Therefore, two variables with the same value outside the cache refer to different objects, and is returns False.
  • The is operator checks object identity, not equality. To compare values, use ==.
  • Practical conclusion: do not rely on is for number comparison; use == if only value equivalence matters, and reserve is for None checks or comparisons with singleton objects.