Small Integers are Cached in Python
Cached Small Integers #
Python caches small integers, and when we create a new integer with the same value, Python reuses the existing object.
For integers between -5 and 256, Python caches the objects and reuses them. This means that when we create a new integer with a value between -5 and 256, Python will reuse the existing object and will use the same memory address.
>>> a = 100
>>> b = 100
>>> id(a)
127790285327696
>>> id(b)
127790285327696
Both a and b have the same memory address, which means they are the same object in memory. Since the ‘is’ operator checks if two objects are the same object in memory, the following code will return True:
>>> a is b
True
Outside the Range #
However for numbers outside the range, Python will create a new object in memory for each integer:
>>> a = 1000
>>> b = 1000
>>> id(a)
127790283952016
>>> id(b)
127790283952496
In this case, a and b have different memory addresses, which means they are different objects in memory. The is operator will return False:
>>> a is b
False
Why Cache Small Integers? #
Caching small integers is a memory optimization. The integers between -5 and 256 are used frequently in programming for indexing, for loops, etc.
However, it is important to remember that this optimization is an implementation detail of CPython, the reference implementation of Python. Other implementations of Python, such as PyPy, Jython, and IronPython, may not have this optimization. So it is always best to avoid relying on this behavior in your code.
Use the == operator to compare integers for equality, and avoid using the is operator to compare integers for identity, even though is is faster than ==.
However, if you need to make a design discussion where an integer lookup is a bootleneck, limit your range to -5 to 256 to take advantage of this optimization.