When giving Python’s basic rules and conventions about parameters and arguments, we stated that “arguments are passed by value except for mutable objects like lists.” In the function calls we have seen so far, Python passes to the function the value a variable currently has, not the variable itself. For example, in the call calculateTax(earnings, 25), the value of earnings (which was 50000) is passed. If we want a function to change variables, we either defined them as global or we used the value the function returned.
When a function has a list as an argument, things are different: Python passes the list itself and thus a change made by the function is a change made to the list. Understanding how lists are handled is crucial when a function operates on a list, as illustrated in the example below.
## function updateGradeList has one argument, a list, and it contains no ## return statement. ## the list contains non-negative integer scores that are changed as follows: ## a score less than 50 gets 10 points added; ## a score 50 or higher and less than 70 gets 5 points added ## all other scores are unchanged ## def updateGradeList(grades): for g in range(0, len(grades)): if grades[g] < 50: grades[g] = grades[g] + 10 elif grades[g] < 70: grades[g] = grades[g] + 5
The function contains one argument and no return statement. Indeed, it is recommended that list grades not be returned. Consider the following function call:
myGrades = [89, 33, 59, 45, 31, 66, 70, 50, 0, 90] updateGradeList(myGrades)
After the function call, we have myGrades = [89, 43, 64, 55, 41, 71, 70, 55, 10, 90].
This illustrates that the changes made by function updateGradeList are seen after the function call. When function updateGradeList operates on list grades, it operates on the same list variable myGrades is bound to. Hence, the changes remain after the function completes. The PythonTutor environment provides an excellent visualization of this situation. For example, if we set myGrades=0 and then call updateGradeList(myGrades). What is the value of myGrades after the call?