为什么 Python 为列表、元组、字典分配新的 id,即使它们具有相同的值?

use*_*825 2 python

x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is y1)
print(x2 is y2)
print(x3 is y3)
Run Code Online (Sandbox Code Playgroud)

输出

True
True
False
Run Code Online (Sandbox Code Playgroud)

为什么 Python 会为 分配不同的 id y3,而不是x3

这里x3y3是列表,但 Python 也对元组和字典做同样的事情。我还想知道 Python 在哪里还有相同的行为,将新的 id 分配给具有相同值的变量,为什么会这样?

小智 5

因为否则会发生这种情况:

\n
x3 = [1,2,3]\ny3 = [1,2,3]\n\nx3[0] = "foo"\nx3[0] == y3[0] # Does NOT happen!\n
Run Code Online (Sandbox Code Playgroud)\n

实际上,

\n
x3[0] != y3[0]\n
Run Code Online (Sandbox Code Playgroud)\n

这是一件好事\xe2\x84\xa2。如果x3y3相同,那么改变其中一个也会改变另一个。这通常是意想不到的。

\n

另请参阅Python何时为相同的字符串分配新的内存?为什么字符串的行为不同。

\n

另外,==如果您想比较值,请使用.

\n