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])
2 Answers 2
With s2 = s1
you just lost the local reference to s2
(i.e 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.
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 (i.e. list and contents) to the variable s2.
s1 = s2
is effectively no-op. Could you please explain a bit more why and what did you expect.