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

Python中id()函数的作用及值相同变量的内存地址是否一致?

Do variables with the same value have the same memory address in Python?

Great question! The short answer is: it depends on the type of object and Python's internal optimizations called object interning.

Let’s break this down with examples, including the ones you shared:

Case 1: Interned immutable objects (same memory address)

Python automatically caches certain commonly used immutable objects (like small integers and short strings) to save memory and boost performance. This means variables holding identical values will point to the exact same memory address.

Your code example perfectly illustrates this behavior:

In [30]: a = 'asdf'
In [31]: hex(id(a))
Out[31]: '0x1082caa08'
In [32]: b = 'asdf'
In [33]: hex(id(b))
Out[33]: '0x1082caa08'

In [34]: c = 2
In [35]: hex(id(c))
Out[35]: '0x1067295c0'
In [36]: d = 2
In [37]: hex(id(d))
Out[37]: '0x1067295c0'

Here, both a/b and c/d share the same memory addresses because Python has interned these frequently used objects.

Case 2: Non-interned immutable objects (different memory addresses)

For larger integers, longer strings, or strings with special characters, Python won’t intern them by default. Even if their values are identical, they’ll be stored as separate objects with distinct memory addresses:

a = 1000000
b = 1000000
print(hex(id(a)) == hex(id(b)))  # Likely outputs False

long_str_a = "this is a very long string that won't be interned automatically"
long_str_b = "this is a very long string that won't be interned automatically"
print(hex(id(long_str_a)) == hex(id(long_str_b)))  # Likely outputs False

Case 3: Mutable objects (always different memory addresses)

Mutable objects like lists, dictionaries, or sets are never interned. Even if two mutable objects have identical content, they are separate instances with unique memory addresses:

list_a = [1, 2, 3]
list_b = [1, 2, 3]
print(hex(id(list_a)) == hex(id(list_b)))  # Outputs False

dict_a = {"key": "value"}
dict_b = {"key": "value"}
print(hex(id(dict_a)) == hex(id(dict_b)))  # Outputs False

Quick Summary

  • Same memory address: Small integers (typically -5 to 256) and short/standard strings (Python’s auto-interned objects)
  • Different memory address: Large integers, non-standard strings, and all mutable objects (lists, dicts, etc.)

内容的提问来源于stack exchange,提问作者Jason Kim

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:46:35