我有这段代码:
list1 = [1, 2, 3]
list2 = list1
list1 = [4, 5, 6]
print(list2)
print(list1)
结果如下:
[1, 2, 3]
[4, 5, 6]
为什么 list2 还没有指向 [4, 5, 6]?我的印象是,由于列表是可变的,因此更改会同时影响 list1 和 list2,因为在 RAM 中,两个列表都指向相同的项目序列。
如有任何解释,我们将不胜感激。
请您参考如下方法:
我在代码中添加了原因作为注释:
# list1 variable points to the memory location containing [1, 2, 3]
list1 = [1, 2, 3]
# list2 variable made to point to the memory location pointed to by list1
list2 = list1
# list1 variable made to point to the memory location containing
# a new list [4, 5, 6], list2 still pointing to [1, 2, 3]
list1 = [4, 5, 6]
print(list2) # list2 prints [1, 2, 3]
print(list1) # list1 prints [4, 5, 6]
