|
> As you can see, it is pass by reference. 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: def swap(a, b):
a, b = b, a
a = [1,2]
b = [3,4]
print(a,b)
swap(a,b)
print(a,b)
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++: template<typename T> // template to be the most equivalent to the intended Python code
void swap(T& a, T& b) {
T t = a;
a = b;
b = a;
}
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). |
That doesn’t change the fact that they are indeed pointers (aka references).
How are pointers to pointers passed? You don’t want to reference another stack frame directly, so you pass by value.