+ 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?
8 Respuestas
+ 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
+ 7
Thank you all for your explanations! :-)
These are the little problems for what I hate Python sometimes.
+ 7
Sorry, my quiz question 😋
Those are exactly pointers at work here, passing by reference not by value.
+ 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
+ 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..
+ 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
+ 2
@Niush +1, except, maybe, for full on functional programming languages...
+ 1
change is an impure function that changes the list in-place. Thus, it DOES change the list you pass it