pass by value and pass by reference in Python

pass by value and pass by reference in Python

pass by value is a scenario where the function is passed a copy of an argument. The function changes the value of this argument but that doesn't affect the actual value passed. Explained by below example:

def value_change(var):
    var = var + 100
    print ("Value of var in the function is",var)

var = 100
value_change(var)

print ("Value of var after the function call is", var)

Output is as below,
Value of var in the function is 200
Value of var after the function call is 100

We can observe that inside the function var value is changed to 100 but even after the function execution, the value outside the function remains 100. 

---------------------------------

pass by reference is a scenario where the function is passed address of the actual variable and the change is reflected outside the function as well. Explained by below example:

def list_change(list):
    list.append('200')
    print ("Value of list in the function is",list)

list = ['100']
list_change(list)

print ("Value of list after the function call is", list)

Output is as below,
Value of list in the function is ['100', '200']
Value of list after the function call is ['100', '200']

We can observe that inside the function list was added element 200 but after the function execution, the list outside the function has both 100,200. 

Post a Comment

0 Comments