Link Search Menu Expand Document

Pass by value and reference

In many programming languages, there are two ways to pass input arguments to a function:

  • πŸ“‹ By value: A local copy of the variable is created. Any modification on it will have no effect on the original one.
  • πŸ”— By reference: The input variable is modified directly. Modifications will affect the original variable.

πŸ“‹ Let’s look at an example of pass by value. As you can see, x does not change. The function acts on a copy and does not modify the original value.

x = 10
def function(input):
    input += 1

function(x)
print(x)
# 10 <- The x does NOT change

πŸ”— Now let’s look at an example of passing by reference. As you can see, x changes. The function acts directly on x.

x = [10]
def function(input):
    input.append(20)

function(x)
print(x)
# [10, 20] <- The x DOES change

This difference can be somewhat complicated to understand in Python, since it is not possible to explicitly indicate whether we want it to be treated by value or by reference as in other languages.

The key difference is that the first example uses an int and the second uses a list. The behavior is defined by the type of variable used:

  • πŸ“‹ Immutable types such as int or string are passed as a value. The function cannot modify the original variable.
  • πŸ”— Mutable types such as list are passed as a reference. The function modifies the original value.

When in doubt, we can use id() to know if two variables refer to the same variable. We can see how the id() is different.

πŸ“‹ Pass by value. The id is different. They are different variables. Modifying one does not modify the other.

x = 10
def function(input):
    input += 1
    print(id(input)) # 4341262928

print(id(x)) # 4341262960
function(x)

πŸ”— Pass by reference. The id is the same. It is the same variable. If you modify one, the other is also modified.

x = [10]
def function(input):
    input.append(20)
    print(id(input)) # 4299629568

print(id(x)) # 4299629568
function(x)

You can see, therefore, how in Python the behavior of passing by value or by reference is directly related to mutable and immutable data types. As a final note, let’s look at some advantages and disadvantages of these types:

  • πŸ“‹ Immutable: Data is protected from modification, which makes it more secure. However, it may require more memory, as they are continuously being copied.
  • πŸ”— Mutable: The original data can be modified. They require less memory, since the original variable is used, without having to copy it. It is very useful when working with types that store a lot of data, where it would not be feasible to copy continuously.