
xenomachina
216
1
6

Beginner Python programmers think that Python uses pass-by-value. Then they get confused when a function modifies an object they passed into it.
Intermediate Python programmers will say "you need to understand the difference between pass-by-value and pass-by-reference", implying that Python uses pass-by-reference.
However, Python does *not* use [pass-by-reference](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference). This is a term that predates Python and has a specific meaning that Python does not adhere to. If Python did use pass-by-reference, then this code...
def f(x):
x = x + 1
a = 1
f(a)
print(a)
...would print "2". However, it prints 1.
It turns out the beginners were right, sort of. Python *does* use [pass-by-value](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value). The confusion comes from the fact that the "values" that variable hold in Python are themselves references. So you're passing by value, but the values are references. Again, **this is *not* the same thing as pass-by-reference**, but a huge fraction of Python programmers get this wrong.
Some people call pass-by-value where the values are references "[pass by sharing](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing)", but it absolutely is not the same as "pass by reference".
This isn't a unique thing about Python, by the way. Java, , C#, and many other garbage collected languages behave this way, with only pass-by-value, but with values (at least most of the time) being references.
lightfoot2
Well yeah. In the functions the variables are recreated and independent of the mainline program. If you said b=f(a) in the main program you'd get b=2, but a is not disturbed just because it is in a function.return value is
lightfoot2
Well yeah. In the functions the variables are recreated and independent of the mainline program. If you said b=f(a) in the main program you'd get b=2, but a is not disturbed just because it is in a function.return value is
xenomachina
There are languages where you can define a function that changes the values that are passed into the function. That's what pass-by-reference is. C++ and Pascal are two examples of languages that do this. In C++:
#include
void f(int &x) {
x = x + 1;
}
int main() {
int a = 1;
f(a);
printf("%d\n", a);
}
xenomachina
A lot of intermediate Python programmers incorrectly believe that Python uses pass by reference, but it does not. It uses pass by value.
The confusion arises because variables hold references, so the values being passed are references. The example code in this post's description shows that this is not the same as pass by reference, though.