How do I pass a variable by reference in Python?

Better Stack Team
Updated on January 26, 2023

In Python, variables are passed to functions by reference. This means that when you pass a variable to a function, you are passing a reference to the memory location where the value of the variable is stored, rather than the value itself.

This is different from some other programming languages, which pass variables by value, meaning that a copy of the value is passed to the function.

Here's an example of how you might pass a variable to a function and modify its value inside the function:

 
def my_function(x):
    x = x * 2
    print(x)

y = 5
my_function(y)
print(y)

This would output the following:

 
10
5

As you can see, the value of y is not modified by the function. This is because the value of x inside the function is a new reference to a different memory location, and it is not connected to the original y variable.

If you want to modify the value of a variable that is passed to a function, you can use a mutable data type such as a list or dictionary. Here's an example using a list:

 
def my_function(x):
    x[0] = x[0] * 2
    print(x)

y = [5]
my_function(y)
print(y)

This would output the following:

 
[10]
[10]

In this case, the value of y is modified by the function because the x variable refers to the same memory location as the y variable.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →