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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github