我有这段代码:
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中,两个列表都指向相同的项目序列。
任何解释都将不胜感激。
答案 0 :(得分:4)
我在代码中添加了 comments 的原因:
# 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]
答案 1 :(得分:3)
我将逐一介绍这些内容:
# Define a list [1, 2, 3] and save it into list1 variable
list1 = [1, 2, 3]
# Define list2 to be equal to list1 (that is, list2 == list1 == [1, 2, 3])
list2 = list1
# Create a new list [4, 5, 6] and save it into list1 variable
# Notice, that this replaces the existing list1!!
list1 = [4, 5, 6]
# Print list2, which still points to the original list [1, 2, 3]
print(list2)
# Print the new list1, [4, 5, 6] that is
print(list1)
但是,这个:
list1 = [1, 2, 3]
list2 = list1
list1.append(4)
print(list2)
print(list1)
将输出:
[1, 2, 3, 4]
[1, 2, 3, 4]
由于我们正在修改list1
(因此list2
,他们 可变),而不是创建新列表并将其保存在变量名称{{1}下}
此处的关键字创建新列表,因此您在示例中未编辑list1
,实际上您正在更改名称list1
指向一个完整的不同列表。
答案 2 :(得分:3)
列表 可变。但是,行:
list1 = [4, 5, 6]
不改变先前由list1
引用的列表对象,它会创建全新的列表对象,并将list1
标识符切换为参考新的。您可以通过查看对象ID来看到这一点:
>>> list1 = [1, 2, 3]
>>> list2 = list1
>>> id(list1)
4379272472
>>> id(list2)
4379272472 # both reference same object
>>> list1 = [4, 5, 6]
>>> id(list1)
4379279016 # list1 now references new object
>>> id(list2)
4379272472 # list2 still references previous object