0

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])
Chris
138k139 gold badges314 silver badges290 bronze badges
asked Jun 21, 2017 at 12:18
4
  • 1
    Because the first thing you do in f is that you re-bind the name s2 to the list referenced by s1. The latter s1 = s2 is effectively no-op. Could you please explain a bit more why and what did you expect. Commented Jun 21, 2017 at 12:23
  • 1
    because python lists are passed by reference. google passing by reference vs passing by value Commented Jun 21, 2017 at 12:25
  • 1
    You should read nedbatchelder.com/text/names.html Commented Jun 21, 2017 at 12:36
  • @IljaEverilä hey that's interesting, thanks! Commented Jun 21, 2017 at 12:38

2 Answers 2

1

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.

answered Jun 21, 2017 at 12:22
1

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.

answered Jun 21, 2017 at 12:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.