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
ischeck returnsTrue. - 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
isreturnsFalse. - The
isoperator checks object identity, not equality. To compare values, use==. - Practical conclusion: do not rely on
isfor number comparison; use==if only value equivalence matters, and reserveisforNonechecks or comparisons with singleton objects.