简体   繁体   中英

Assigning lists to eachother in Python

Can someone explain me why this python code prints 6 instead of -10?

Why does s2/list2 not change throughout this piece of code?

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.

That line assigns the value (ie list and contents) to the variable s2.

With s2 = s1 you just lost the local reference to s2 (ie list2 ). From there on, you're altering s1 ( list1 ), assigning -7 to list1[2] and then -10 .

You aren't changing list2 in any way. Use a different name in the assignment to get it to work, s = s1 , for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM