Pass by Value vs Pass by Reference in Python
When we call a function and pass data to it, Python handles it either by reference or value, depending on the type of data.
In simple words:
- Pass by Value: A copy of the variable is passed. Changes do not affect the original data.
- Pass by Reference: The original reference is passed. So changes inside the function reflect outside too.
But in Python, the concept is slightly different. Python uses pass by object reference (also known as **pass by assignment**).
What is Pass by Value?
In pass by value, a copy of the actual data is sent to the function.
This means any changes made inside the function do not change the original data.
In Python, immutable data types like int, float, string,
and tuple
behave like pass by value.
Example:
def increase(x):
x = x + 10
print("Inside function:", x)
a = 5
increase(a)
print("Outside function:", a)
Output:
Inside function: 15
Outside function: 5
Explanation:
ais an integer (immutable).- Inside the function,
xgets a copy ofa. - Changing
xdoes not changea. - This behaves like pass by value.
What is Pass by Reference?
In pass by reference, the address (reference) of the actual data is sent to the function. So changes inside the function directly modify the original data. This happens with mutable data types such as lists, dictionaries, sets.
Example:
def add_item(my_list):
my_list.append(100)
print("Inside function:", my_list)
numbers = [10, 20, 30]
add_item(numbers)
print("Outside function:", numbers)
Output:
Inside function: [10, 20, 30, 100]
Outside function: [10, 20, 30, 100]
Explanation:
numbersis a list (mutable).- Inside the function,
my_listpoints to the same list asnumbers. - So when we modify
my_list, it also changesnumbers. - This behaves like pass by reference.
Real-life analogy:
- Pass by Value: Giving your friend a photocopy of your marksheet. If they write on it, your original stays safe.
- Pass by Reference: Giving your friend the original marksheet. If they write on it, your actual marksheet changes.
Summary:
| Pass by Value | Pass by Reference |
|---|---|
| Function gets a copy of the data. | Function gets the actual data (reference). |
| Original data does not change. | Original data changes if modified inside the function. |
| Works with immutable types like int, float, string, tuple. | Works with mutable types like list, dict, set. |
| Safe for original data. | Risk of changing original data. |