Search⌘ K
AI Features

Pass by Reference

Explore the concept of pass by reference in Python, focusing on how mutable objects behave when passed to functions. Understand the differences between object modification and replacement, and learn to manage references safely in object-oriented code.

We'll cover the following...

This lesson will unfold a very tiny but tricky concept that can bring a cascading effect to our code if not handled with care.

Passing a parameter to a function

A function can change any mutable object passed as a parameter, but it can never replace it with another object. To understand it, let’s jump straight to an example. Consider the following function:

def function(x, y):
    x += y
    return x

Now, let’s call this function in different ways and see the difference.

Python 3.10.4
def function(x, y):
x += y
return x
x = 1
y = 2
function(x, y) # Calling for ints
print(x)
x = [1, 2]
y = [3, 4]
function(x, y) # Calling for lists
print(x)
x = (1, 2)
y = (3, 4)
function(x, y) # Calling for tuples
print(x)

You may have noticed that x doesn’t change after calling function(), when it was an integer or a tuple. But in the case of a list (see line 12), its value does change, and becomes equal to x+y, i.e., [1, 2, 3, 4].