|
|
|
|
|
by hajile
1374 days ago
|
|
I think I see what you are saying (the shared variable threw me), but it STILL isn't doing what you think. def s(x):
x[1] = 2222
return x
x = [1,2,3]
print(s(x)) # prints [1, 2222, 3)
As you can see, it is pass by reference.Tuples, strings, numbers, and some other things are immutable. When you pass them, you pass a reference (from the user's perspective as this can be optimized to pass by value as the interpreter sees fit). When you update that reference, because they are immutable, you must update the current reference to a new location in memory. Because you are changing what the new pointer variable in the function points to, of course the other pointer doesn't update. |
|
No, it's passing a reference, but it is still not pass by reference, this is actually worth distinguishing because they are different behaviors. That function (by moonchild) does exactly what moonchild meant it to do, which was to demonstrate that Python is not pass by reference. Another function demonstrating that Python is not pass by reference:
If Python were pass by reference (versus passing a reference in these cases) then it would perform a swap, but it does not perform a swap because it is not pass by reference. C++ has pass by reference (as an option), as do Pascal and Ada, and more languages. But Python is not among them. An actual pass-by-reference swap, in C++: That will actually perform a swap when called with `swap(x,y)`. Any language that offers (by option or by default) pass by reference can have an equivalent swap function, including a generic one like the above if the language offers some notion of generics or is dynamically typed (like Python).