Pass by assignment

Published

2023-07-31

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 = z + 1
    return z
    
x = 5
y = f(x)

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
    
x = 1
y = 2

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.

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).