Python中小于-5和大于256的整数对象内存机制探究
Great question! Let's unpack what's happening here with Python's integer objects step by step.
First, let's recap the small integer caching you mentioned: Python pre-allocates memory for integers in the range -5 to 256 and reuses these objects throughout your program. This is an optimization to save memory and speed up common operations, since these integers are used so frequently.
Why 256 has the same ID every time
When you run:
print(id(256)) a = 256 print(id(a))
Both calls return the same ID because you're referencing the pre-cached 256 object every time. Python doesn't create a new object here—it just points the variable a to the existing cached instance.
Why 300 has different IDs
For integers outside the -5 to 256 range, Python does dynamically create new objects—and the behavior you're seeing is also tied to how the interactive Python shell works:
- When you run
print(id(300)), Python creates a new 300 object, prints its ID, and since no variable is referencing this object, it gets marked for garbage collection right away. - Next, when you run
a = 300, Python creates a brand new 300 object (the previous one was already cleaned up) and assigns it toa. That's why the IDs are different—they're two separate integer objects, even though they represent the same value.
If you test this in a single line of code (instead of separate lines in the shell), you'll see the same ID for both 300 instances, because Python reuses the object within the same expression context:
print(id(300), id(300)) # Outputs the same ID twice
To sum up:
- Pre-cached integers (-5 to 256) are always reused, so their IDs stay consistent.
- Integers outside this range are dynamically created as needed. In the interactive shell, if you create them in separate lines without keeping a reference, the old object is discarded, and a new one is made the next time you use the same value.
内容的提问来源于stack exchange,提问作者galaxyan

