为何Python中同值列表内存地址不同,字符串却相同?
Great question! This boils down to two key Python concepts: immutability and an optimization called string interning. Let’s break it down with your example in mind:
首先看字符串的情况
Your string variables var1 and var2 are assigned to the exact same string literal: 'test test'. Python automatically uses a trick called string interning here.
Since strings are immutable—meaning you can’t change the characters in a string once it’s created—Python can safely reuse the same memory object for identical string literals. This saves memory because it avoids storing duplicate copies of the same string value.
In your code, id(var1) == id(var2) returns True because both variables point to the single interned string object in memory.
再看列表的情况
Lists are mutable—you can add, remove, or modify elements in a list after it’s created. Because of this, Python can’t safely reuse the same list object for two different variables, even if their initial contents are identical.
Imagine if list1 and list2 pointed to the same memory address: if you did list1.append(15), list2 would also get that new element, which is almost never what you want when creating two separate list variables.
So Python allocates a new memory block for each list literal you define, hence id(list1) == id(list2) returns False.
快速验证小技巧
If you want to force string interning for dynamic strings (not just literals), you can use the sys.intern() function:
import sys var3 = sys.intern('test test') print(id(var1) == id(var3)) # Still True
And for lists, even if you try to copy a list, the new list will have a different ID (unless you use a reference assignment like list3 = list1, which makes them point to the same object):
list3 = list1.copy() print(id(list1) == id(list3)) # False
内容的提问来源于stack exchange,提问作者Mehedi Hasan

