Transcript for:
Understanding Python Argument Passing

We have used many different types in our Python programs. Some of these types are value types, including int, float, and bool. When a value type is passed in as an argument to a function, a copy is made. This is called passing by value. Changes made to the copy inside the function have no permanent effect. In this case, a copy of the local variable a is passed into the function for the parameter x. Changes made to x inside the function do not change the variable a, and so a will still be 2 after the function is executed. Types like arrays and lists work differently. When the elements inside the list are changed in a function, the changes are permanent and persist after the function returns. These types are called reference types, because a reference to the original value is passed into the function, not a copy. This is called passing by reference. In this case, a list is created outside of the change function, but then a reference to that list is passed into the function for the parameter x. Now we have two references to the exact same list. Both a and x refer to the same list. Changes made to x inside the function persist, and so the 2 at index 0 in the list has been replaced for both x and a. If you print the list after the function returns, you will see that it has been permanently modified. Now let's take a closer look at those two simple examples. a is initialized to the integer value 2 on line 20, and then we call the add5 function on line 21. The first thing we do inside the add5 function is modify the value for the parameter x by adding 5 to it and then printing it out. We can see that that is 7. However, when we print a after the add5 function returns on line 22, we can see that the original value has not been changed. a still has a value of 2. The copy that was modified in the add5 function has no effect on the original variable outside of the function. This time, we create the list b on line 28 in the program with a single value of 2 at index 0. Then, when we call the change function, the very first thing that it does with the parameter x is modify the value at index 0 in the list so that it is 10 and then print it out. We can see the result. The list contains the single value 10, not 2. That 2 has been replaced. When we print the original list on line 30 of the main function, we can see the same thing. Because b and x are both references to the same list, the changes that we made to x inside of the change function persist after the function returns, and we can see that when we print out the variable b.