Call by value and Call by reference are the two types of generic methods to pass parameters to a function.
C++ uses call by value method while Java uses call by reference method.
But what does Python use? does Python use call by value or call by reference to pass parameters to a function?
Let's find out ......
Example 1
def add_num(number):
number += 1
n = 12
add_num(n)
print(n) # 12
here it does not change value of n at all. So it seems Python uses call by value method to pass the parameters.
But is it correct?
let's see another example to confirm it...
Example 2
def add_element(num_list):
num_list.append(5)
my_list = [1,2,3,4]
add_element(my_list)
print(my_list) # [1,2,3,4,5]
That's Weird!
Example 2 tells us that Python uses call by reference method to pass the parameters.
These are two contradicting examples by themselves !
Don't get confused , let's decode what's actually going on here
Explanation
first of all remember a simple basic thing about Python i.e everything in Python is an Object.
In the 2nd example when we call the function add_element and pass my_list as the parameter we are passing the entire object as a parameter and that object gets mapped onto num_list.
So now num_list and my_list are pointing to the same list i.e [1,2,3,4] so now any changes made to this list whether by my_list or by num_list will be made in the original list
If you want to confirm this you can use the id() function on both my_list and num_list and can see the same for yourself.
This type of parameter passing method is known as call by object.
In this method you pass the entire object as the parameter and then all the changes made to this object is global
Now you would ask , in example 1 isn't n also an Int object? So technically the value of n should also change , but it doesn't.
Why?
let's solve that mystery also...
let's go to basics again.
In the 2nd example we have used a list object and lists are mutable while in the 1st example we have used an Int object and Int is immutable.
So what actually is happening in example 1 is when we increment the value of n since Int is immutable the function creates a new container and stores in it the incremented value of n while the original n stays the same.
Conclusion
So to conclude , Python uses call by object method to pass around the parameters and it depends on the object type whether it uses call by value or call by reference method underneath .
when you pass the function an immutable object Python uses call by value method .
when you pass the function a mutable object Python uses call by reference method.
Hope your confusion is clear
If you still have some doubts feel free to connect with me on Twitter
Top comments (0)