Why can a function modify some arguments as perceived by the caller, but not others?
Some answers contain the word "copy" in a context of a function call. I find it confusing.
Python doesn't copy objects you pass during a function call ever.
Function parameters are names. When you call a function Python binds these parameters to whatever objects you pass (via names in a caller scope).
Objects can be mutable (like lists) or immutable (like integers, strings in Python). Mutable object you can change. You can't change a name, you just can bind it to another object.
Your example is not about scopes or namespaces, it is about naming and binding and mutability of an object in Python.
def f(n, x): # these `n`, `x` have nothing to do with `n` and `x` from main()
n = 2 # put `n` label on `2` balloon
x.append(4) # call `append` method of whatever object `x` is referring to.
print('In f():', n, x)
x = [] # put `x` label on `[]` ballon
# x = [] has no effect on the original list that is passed into the function
Here are nice pictures on the difference between variables in other languages and names in Python.
You've got a number of answers already, and I broadly agree with J.F. Sebastian, but you might find this useful as a shortcut:
Any time you see varname =
, you're creating a new name binding within the function's scope. Whatever value varname
was bound to before is lost within this scope.
Any time you see varname.foo()
you're calling a method on varname
. The method may alter varname (e.g. list.append
). varname
(or, rather, the object that varname
names) may exist in more than one scope, and since it's the same object, any changes will be visible in all scopes.
[note that the global
keyword creates an exception to the first case]
f
doesn't actually alter the value of x
(which is always the same reference to an instance of a list). Rather, it alters the contents of this list.
In both cases, a copy of a reference is passed to the function. Inside the function,
n
gets assigned a new value. Only the reference inside the function is modified, not the one outside it.x
does not get assigned a new value: neither the reference inside nor outside the function are modified. Instead,x
’s value is modified.
Since both the x
inside the function and outside it refer to the same value, both see the modification. By contrast, the n
inside the function and outside it refer to different values after n
was reassigned inside the function.