+ 8

Python, strange effect, but why?

Hi @ all, I did just stumble over a challenge: def change(ls): ls[1] = 6 lst = [5,8] change(lst) print(sum(lst)) The result is 11, but why? I would have supposed that 13 is the result. The function does not have a return-statement, so the code outside the function should not be affected by the code within the function. Or is this because of the mutable character of lists in Python?

9th Mar 2018, 7:48 AM
Jan Markus
8 Respostas
+ 6
Pointers Pointers Everywhere. Unlike Normal Variables, List have pointers so even when they are passed from parameters they get change. Results 6 + 5 = 11 Search "Pointers" for more
9th Mar 2018, 8:05 AM
Niush
Niush - avatar
+ 7
Thank you all for your explanations! :-) These are the little problems for what I hate Python sometimes.
9th Mar 2018, 9:46 AM
Jan Markus
+ 7
Sorry, my quiz question 😋 Those are exactly pointers at work here, passing by reference not by value.
9th Mar 2018, 4:27 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
@ Kuba Siekierzynski: That is a real nasty question. ;-) I have now found a very good explanation for my initial question here: https://www.quora.com/What-is-the-pointer-in-JUMP_LINK__&&__Python__&&__JUMP_LINK-Does-a-pointer-exist-in-Python
9th Mar 2018, 5:25 PM
Jan Markus
+ 5
I don't know a lot in python.. but i think that you are change the ls[1] which was 8 to 6.. so the array become lst=[5,6].. and the sum will be 5 + 6 = 11.. sorry if i am wrong but i am beginner in python..
9th Mar 2018, 7:52 AM
Baraa AB
Baraa AB - avatar
+ 3
In addition to your quora link: "mutable" is the ticket. If you want to dig further, Python actually calls "by assignment" and not by reference (even if you're getting by-reference-like behavior here). The distinction is important because rebinding is LOCAL, which is demonstrated / explained here: https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference and documented here, with specific mentions for "mutable": https://docs.python.org/3/faq/programming.html#how-do-i-write-a-function-with-output-parameters-call-by-reference
9th Mar 2018, 9:54 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
@Niush +1, except, maybe, for full on functional programming languages...
9th Mar 2018, 9:52 AM
Amaras A
Amaras A - avatar
+ 1
change is an impure function that changes the list in-place. Thus, it DOES change the list you pass it
9th Mar 2018, 9:10 AM
Amaras A
Amaras A - avatar