I have two codes for passing parameters to a function in Python.
1-
def changeme( mylist ):
mylist.append([1,2,3,4]);
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
2-
def changeme( mylist ):
mylist = [1,2,3,4];
print "Values inside the function: ", mylist
return
mylist = [10,20,30];
changeme( mylist );
print "Values outside the function: ", mylist
Why in the first code mylist is passed by reference, and in second code it is passed by value?
You need to realize that assignment in python does not operate on the object that is on the left hand side. Assignment creates a new reference to the object on the right hand side and stores that reference in the name on the left hand side. So, in your 1st example you mutate the list which you input and you see that change later. In the 2nd example, inside your function you create a new reference to a list (which is created on the right hand side) and bind that to the local (to the function) variable
mylist. Thereforemylistno longer references the object which you input to the function.