Course contentsShow
← Python
Lesson 27 of 1,0601. Foundations and EnvironmentFree lesson

Understanding Python Integer Caching and Interning

You will discover how Python optimizes memory by reusing small integer objects and short strings to improve program performance.

Understanding Python Integer Caching and Interning

In this lesson, you will learn how Python saves memory and boosts speed by "recycling" small integers and specific strings behind the scenes.

The Memory Efficiency Trick

When you assign a variable to a value like 5, Python creates an object in your computer's memory. If you assign another variable to the same value, you might expect Python to create a second, identical object. However, Python is smart! For frequently used values, Python pre-allocates them when it starts up. This process is called caching (or interning).

Python automatically caches all integers between -5 and 256. Because these numbers are used constantly in loops and counting, Python keeps them in a permanent memory location. Whenever your code uses one of these numbers, Python simply points your variable to the existing object instead of creating a new one.

Seeing it in Action

We can use the id() function to see the memory address of our variables. Remember that the is operator checks if two variables point to the exact same object in memory.

# Small integers are cached
a = 100
b = 100
print(a is b)  # Output: True (They share the same memory address)

# Larger integers are not cached (usually)
x = 1000
y = 1000
print(x is y)  # Output: False (Python created two separate objects)

In the first example, a and b share the same identity because 100 is inside the "small integer" cache range. In the second example, 1000 falls outside that range, so Python treats them as distinct objects, even though their values are the same.

Why Does This Matter?

This optimization makes your programs slightly faster and helps reduce memory usage. You don't need to manually manage this—Python handles it automatically so you can focus on writing your logic. Just remember that while two integers might have the same value (==), they might not have the same identity (is) if they are larger numbers, because Python isn't required to cache them.

Key Takeaway: Python automatically caches small integers (from -5 to 256) to improve performance, ensuring that variables assigned to these values share the same identity in memory.