Hi Pythonistas!
Today we are going to discuss a simple topic that confuses most of the developers. Which is an argument in the Python- pass by value or pass by reference?
Actually, Python has both or simply we can say that it is passed by assignment. Pass by value or reference is decided on the basis of the argument passed and operation performed on it.
Example 1
In [1]: def pass_by_value(name):
...: name = f"Hello {name}"
...: print(name)
...:
In [2]: a = "Professor"
In [3]: pass_by_value(a)
Hello Professor
In [4]: print(a)
Out[4]: 'Professor'
Example 2
In [5]: def pass_by_reference(data):
...: data.extend(data)
...: print(data)
...:
In [6]: b = ["Professor", "Lisbon", "Nairobi", "Tokyo", "Berlin"]
In [7]: pass_by_reference(b)
['Professor', 'Lisbon', 'Nairobi', 'Tokyo', 'Berlin', 'Professor', 'Lisbon', 'Nairobi', 'Tokyo', 'Berlin']
In [8]: print(b)
Out[8]:
['Professor',
'Lisbon',
'Nairobi',
'Tokyo',
'Berlin',
'Professor',
'Lisbon',
'Nairobi',
'Tokyo',
'Berlin']
Example 3
In [9]: def mutable_reassignment(data):
...: data = data * 2
...: print(data)
...:
In [10]: mutable_reassignment(b)
['Professor', 'Lisbon', 'Nairobi', 'Tokyo', 'Berlin', 'Professor', 'Lisbon', 'Nairobi', 'Tokyo', 'Berlin', 'Professor', 'Lisbon', 'Nairobi', 'Tokyo', 'Berlin', 'Professor', 'Lisbon', 'Nairobi', 'Tokyo', 'Berlin']
In [11]: print(b)
Out[11]:
['Professor',
'Lisbon',
'Nairobi',
'Tokyo',
'Berlin',
'Professor',
'Lisbon',
'Nairobi',
'Tokyo',
'Berlin']
Let’s look at the examples one by one.
In the first example, the argument to the function is as string which is immutable. Therefore the argument behaves like a pass-by value. So a change in the name variable 'name' will not affect variable 'a'.
In the second example, the argument passed to the function is a list which is mutable. In that function we are changing the value of that variable 'data'. This will reflect in variable b as both pointing to same memory location. In this case, it behaves like a pass-by reference.
In the third example, the argument passed to function is again mutable but the value of the input doesn’t change after the execution. The reason is that there is an assignment operation inside the function. The reference of the variable changes during assignment and hence the input variable remains unaffected.
Conclusion:
1 Immutable argument always behave like pass by value
2 Mutable arguments behave like a pass-by reference if there is only mutation. In case of reassignment, this will behave like pass by value.
Hope you have understood the concept.
Happy Coding !!