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:

  1. Download and save the pass_args.py Python file and then open it in VS Code.
  2. Run the pass_args.py program on your computer. Examine the code and the output and answer the following three questions:
    1. In main, there are two local variables named x and lx. At line 14, both of these local variables are passed to the modify_args function. After the call to modify_args finished, which of main’s two local variables did the modify_args function change?
      1. x
      2. lx
      3. both of them
      4. neither of them
    2. Why is the modify_args function NOT able to change main’s local variable x?
      1. Because x is a number and therefore passed to a function by value
      2. Because x is a list and therefore passed to a function by reference
    3. Why is the modify_args function able to change main’s local variable lx?
      1. Because lx is a number and therefore passed to a function by value
      2. 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.