Pass by assignment
Passing arguments to a function
What happens when we pass arguments to a function in Python? When we call a function and supply an argument, the argument is assigned to the corresponding formal parameter. For example:
def f(z):
= z + 1
z return z
= 5
x = f(x)
y
print(x) # prints 5
print(y) # prints 6
When we called this function supplying x
as an argument we assigned the value x
to z
. It is just as if we wrote z = x
. This assignment takes place automatically when we call a function and supply an argument.
If we had two (or more) formal parameters it would be no different.
def add(a, b):
return a + b
= 1
x = 2
y
print(add(x, y)) # prints 3
In this example, we have two formal parameters, a
and b
, so when we call the add
function we must supply two arguments. Here we supply x
and y
as arguments, so when the function is called Python automatically makes the assignments a = x
and b = y
.
It would work similarly if we were to supply literals instead of variables.
print(add(12, 5)) # prints 17
In this example, the assignments that are performed are a = 12
and b = 5
.
You may have heard the terms “pass by value” or “pass by reference.” These don’t really apply to Python. Python always passes arguments by assignment. Always.
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.