07 Checkpoint: Lists
Purpose
Reinforce your understanding that numbers are passed to a function by value and lists are passed to a function by reference.
Problem Statement
Within a Python program, when a number is passed as an argument to a function, the computer copies the number from the argument into the parameter. In other words, the parameter gets a copy of the value that is in the argument. However, when a list is passed as an argument to a function, the computer does not copy the list. Instead, the computer copies a reference to the list into the parameter. This means the argument and parameter refer to the same list. If a called function changes a list that was passed to the function, this will change the list in both the calling and called functions because both the argument and parameter refer to the same list.
Assignment
During this checkpoint, you will examine and run a Python program that passes both a number and a list to function. Do the following:
- Download and save the pass_args.py Python file and then open it in VS Code.
- Run the
pass_args.py
program on your computer. Examine the code and the output and answer the following three questions:- In
main
, there are two local variables named x and lx. At line 14, both of these local variables are passed to themodify_args
function. After the call tomodify_args
finished, which ofmain
’s two local variables did themodify_args
function change?- x
- lx
- both of them
- neither of them
- Why is the
modify_args
function NOT able to changemain
’s local variable x?- Because x is a number and therefore passed to a function by value
- Because x is a list and therefore passed to a function by reference
- Why is the
modify_args
function able to changemain
’s local variable lx?- Because lx is a number and therefore passed to a function by value
- Because lx is a list and therefore passed to a function by reference
Sample Run
> python pass_args.py main() Before calling modify_args(): x 5 lx [7, -2] modify_args(n, alist) Before changing n and alist: n 5 alist [7, -2] After changing n and alist: n 6 alist [7, -2, 4] After calling modify_args(): x 5 lx [7, -2, 4]
Submission
When complete, report your progress in the associated I‑Learn quiz.