You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中小于-5和大于256的整数对象内存机制探究

Understanding Integer Object Creation in Python

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:

  1. 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.
  2. Next, when you run a = 300, Python creates a brand new 300 object (the previous one was already cleaned up) and assigns it to a. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:32:46