Integer and String identity

suggest change

Python uses internal caching for a range of integers to reduce unnecessary overhead from their repeated creation.

In effect, this can lead to confusing behavior when comparing integer identities:

>>> -8 is (-7 - 1)
True
>>> -3 is (-2 - 1)
True

and, using another example:

>>> (255 + 1) is (255 + 1)
True
>>> (256 + 1) is (256 + 1)
True

Wait what?

On Python 3.14.6 all four comparisons are True. CPython folds the arithmetic and reuses one constant inside a single expression, so the old False results for -8 and 257 do not show up here. Integers in the range [-5, 256] are still cached during interpreter startup and created once. Integers outside that range are still created separately when the expressions are compiled separately: two separate evaluations of 256 + 1 are not identical, while two evaluations of 255 + 1 are.

This is a common pitfall since this is a common range for testing, but often enough, the code fails later in staging (or worse, in production) with no apparent reason after working perfectly in development.

The solution is to always compare values using the equality (==) operator and not the identity (is) operator.


Python also keeps references to some strings and can result in similarly confusing behavior when comparing identities (i.e. using is) of strings. These comparisons also emit SyntaxWarning: "is" with 'str' literal.

>>> 'python' is 'py' + 'thon'
True

Inside one expression, CPython folds 'py' + 'thon' and can reuse one constant. It also interns strings that look like identifiers, so separately compiled references to 'python' can still be the same object. That is not a promise that equal strings are identical.

>>> 'this is not a common string' is 'this is not' + ' a common string'
True
>>> 'this is not a common string' == 'this is not' + ' a common string'
True

The is line is True here because both sides are folded in one expression. Evaluated as two separate expressions, those uncommon strings are not the same object, while == is still True.

So, just like the rule for Integers, always compare string values using the equality (==) operator and not the identity (is) operator.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents