Python (specifically the default CPython implementation) uses integer caching to optimize performance and memory usage by pre-allocating a range of commonly used small integer objects.
How Integer Caching Works
- Cached Range: CPython pre-loads all integer objects in the range of -5 to 256 during interpreter startup.
- Singleton Instances: When you assign a variable an integer value within this range, Python simply returns a reference to the existing, pre-allocated object rather than creating a new one. This makes each integer in this range a singleton.
- Memory and Performance: This optimization saves significant memory and computation time because small integers are used very frequently (e.g., as loop counters or list indices).
- Immutability: Integer caching is safe because integers are immutable data types. Sharing the same object across multiple variables does not cause issues, as any operation that appears to modify an integer actually creates a new integer object.
- Within the Cached Range:
- >>> a = 100
- >>> b = 100
- >>> a is b
- True
- >>> id(a) == id(b)
- True
- and point to the same memory location because 100 is within the range.
- Outside the Cached Range (in the Python REPL):
- >>> x = 257
- >>> y = 257
- >>> x is y
- False
- >>> id(x) == id(y)
- False
- and are different objects with different memory locations because 257 is outside the cached range.
- When running a whole script, the Python compiler can optimize and reuse identical integer literals even outside the standard range, making return for .
- In the REPL, code is compiled line-by-line, limiting this optimization and making the distinct object creation more apparent.