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
Here, 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:
This works because lists are mutable. The function modifies the object in place, so the change is visible outside.
Watch a video course: Python - The Practical Guide
Idiomatic Python approach
The standard Python practice is to return the new value instead of trying to modify the original variable: