W3docs

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

python— editable, runs on the server

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:

python— editable, runs on the server

This 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"> Watch a course <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:

python— editable, runs on the server