Python:什么时候两个变量指向内存中的同一个对象? [英] Python: When do two variables point at the same object in memory?
问题描述
这是一个例子:
l = [1, 5, 9, 3]
h = l
h[0], h[2] = h[2], h[0]
print(h) # [9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
h = h*2
print(h) # [9, 5, 1, 3, 9, 5, 1, 3]
print(l) # [9, 5, 1, 3]
我的理解是调用设置 h = l
只会将 h
指向 l
指向的内存中的同一项目.那么为什么在最后 3 行中,h
和 l
没有给出相同的结果?
My understanding was that calling setting h = l
would simply point h
at the same item in memory that l
was pointing at. So why is it that in the last 3 lines, h
and l
don't give the same results?
推荐答案
分配确实使 h 指向与 l 相同的项目.但是,它不会将两者永久焊接在一起.当你用 h = h * 2 改变 h 时,你告诉 Python 在内存中的其他地方构建一个双倍版本,然后让 h 指向翻倍的版本.您没有给出任何更改l的说明;仍然指向原始项目.
The assignment does make h point to the same item as l. However, it does not permanently weld the two. When you change h with h = h * 2, you tell Python to build a doubled version elsewhere in memory, and then make h point to the doubled version. You haven't given any instructions to change l; that still points to the original item.
这篇关于Python:什么时候两个变量指向内存中的同一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!