How do I pass a variable by reference?
In Python, you can pass a variable by reference by using the & operator.
In Python, arguments are passed by assignment. This means the function receives a reference to the object, but you cannot rebind the original variable from inside the function. Whether a change is visible outside depends on whether the object is mutable or immutable.
Calling a function with an immutable variable
def increment(n):
n += 1
x = 1
increment(x)
print(x) # Output: 1Here, n += 1 creates a new integer and rebinds the local name n. The original x remains unchanged.
Modifying a mutable object
To simulate pass-by-reference behavior, you can pass a mutable container like a list:
def increment(n):
n[0] += 1
x = [1]
increment(x)
print(x[0]) # Output: 2This works because lists are mutable. The function modifies the object in place, so the change is visible outside.
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
Idiomatic Python approach
The standard Python practice is to return the new value instead of trying to modify the original variable:
def increment(n):
return n + 1
x = 1
x = increment(x)
print(x) # Output: 2