[英]Assigning lists to eachother in Python
Can someone explain me why this python code prints 6 instead of -10? 有人可以解释一下为什么这个python代码显示6而不是-10吗?
Why does s2/list2 not change throughout this piece of code? 为什么s2 / list2在这段代码中没有变化?
def f(s1,s2):
s2 = s1
s1[2] = -7
s1 = s2
s2[2] = -10
list1 = [1,2,3]
list2 = [4,5,6]
f(list1,list2)
print(list2[2])
After the line s2 = s1
inside the function, the s2 you passed in is no longer relevant inside the function. 在函数内部的行
s2 = s1
之后,您传入的s2在函数内部不再相关。
That line assigns the value (ie list and contents) to the variable s2. 该行将值(即列表和内容)分配给变量s2。
With s2 = s1
you just lost the local reference to s2
(ie list2
). 随着
s2 = s1
您只是失去了对s2
的本地引用(即list2
)。 From there on, you're altering s1
( list1
), assigning -7
to list1[2]
and then -10
. 从那里开始,您要更改
s1
( list1
),将-7
分配给list1[2]
,然后分配-10
。
You aren't changing list2
in any way. 您不会以任何方式更改
list2
。 Use a different name in the assignment to get it to work, s = s1
, for example. 在分配中使用其他名称以使其正常工作,例如
s = s1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.