Bird
Raised Fist0
PythonConceptBeginner · 3 min read

What is Pass by Reference in Python: Explanation and Examples

In Python, pass by reference means that when you pass a variable to a function, the function gets a reference to the original object, not a copy. This allows the function to modify the object if it is mutable, like a list or dictionary.
⚙️

How It Works

Imagine you have a box with a toy inside. When you give someone the box, you are not giving them a new toy, just the same box with the toy inside. In Python, variables hold references to objects (the toys), and when you pass a variable to a function, you give the function the reference (the box), not a new copy of the object.

If the object inside the box can be changed (like a list), the function can change it and you will see those changes outside the function. But if the object is something that cannot be changed (like a number or a string), the function cannot change the original object, only its own copy of the reference.

💻

Example

This example shows how a function can change a list passed to it because lists are mutable objects.

python
def add_item(my_list):
    my_list.append(4)

numbers = [1, 2, 3]
add_item(numbers)
print(numbers)
Output
[1, 2, 3, 4]
🎯

When to Use

Use pass by reference when you want a function to modify an object directly, such as updating a list, dictionary, or custom object. This is helpful when you want to avoid copying large data and want changes to persist after the function ends.

For example, updating a shopping cart list, modifying settings stored in a dictionary, or changing attributes of an object inside a function all benefit from this behavior.

✅

Key Points

  • Python variables hold references to objects, not the actual data.
  • Mutable objects (like lists) can be changed inside functions via their references.
  • Immutable objects (like integers, strings) cannot be changed inside functions.
  • Understanding this helps avoid bugs related to unexpected changes or no changes.
✅

Key Takeaways

Python passes references to objects, not copies, when calling functions.
Mutable objects can be changed inside functions, affecting the original object.
Immutable objects cannot be changed inside functions; only local copies of references exist.
This behavior helps manage memory and performance by avoiding unnecessary copying.
Knowing this prevents confusion about when changes inside functions affect original data.