列表包含对对象的引用。如果这些对象是可变的,则列表可能会在可变对象更改时发生更改。事实上,列表并没有改变,只是被引用的对象的内容。您可以使用该id()
命令查看引用并查看它们没有更改。
您的代码正在改变原始[24, None]
列表。这里有一些额外的print
语句来看看发生了什么:
L = [24, None] # Creates a list, which is a mutable object
print(id(L)) # Here is its unique ID.
t = [13, None]
t[1] = L
L = t
t = [28, None]
t[1] = L[1]
L[1] = t
print(L,id(L[1][1])) # Current contents of L, contains the same mutable list
t = [3, None]
p = L
while p:
q = p # q = [13, [28, [24, None]]], [28, [24, None]], [24, None]
p = p[1] # p = [28, [24, None]] , [24, None] , None
print(L,id(L[1][1])) # Here is L again, still contains the same mutable list
print(q,id(q)) # q also references the same mutable list
if p == L: # False
L = t
else:
q[1] = t # Mutate that same list!
print(L)
下面输出。请注意,[24, None]
列表在所有情况下都具有相同的 ID,因此当您更改 中的None
元素时q
,L
具有对相同列表的引用并且似乎也发生了变化。
64809160
[13, [28, [24, None]]] 64809160
[13, [28, [24, None]]] 64809160
[24, None] 64809160
[13, [28, [24, [3, None]]]]
这是一个更简单的例子:
>>> q = [1,2,3] # Create a list named 'q'
>>> L = [24, q] # Put that list in L
>>> L
[24, [1, 2, 3]]
>>> q[1] = 5 # change 'q'
>>> L # L appears to change. It references the same list.
[24, [1, 5, 3]]