Now let's look at how all this relates to function arguments and return values. When we call a function, we literally create new name bindings — those declared in the function definition — to existing objects — those passed in at the call itself. As such, it's important to really understand Python reference semantics if you want to know how your functions work.
To demonstrate Python's argument passing semantics, we'll define a function at the REPL which appends a value to a list and prints the modified list. First we'll create a list and give it the name m
:
>>> m = [9, 15, 24]
Then we'll define a function modify()
which appends to, and prints, the list passed to it. The function accepts a single formal argument named k
:
>>> def modify(k): ... k.append(39) ... print("k =", k) ...
We then call modify()
, passing our list m
as the actual argument:
>>> modify(m) k = [9, 15...