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
orstring
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.