07 Checkpoint: Lists
Purpose
Reinforce your understanding that Python numbers are immutable and Python lists are mutable.
Problem Statement
Within a Python program, variables of type boolean, integer,
float, and string are immutable which means after a value
is assigned to one of those variables, the value cannot be changed.
When a computer executes a line of code that appears to change a
boolean, integer, float, or string, the computer doesn’t change the
old value of the variable but instead creates a new value and
assigns the new value to the variable. For example, on
line 4 in
example 1 the int
function creates and returns an
integer value that the computer assigns to the variable
x. Line 5
appears to change the value of x by adding 5 to it, but
what really happens is the computer creates a new integer value that
is 5 larger than the old value and assigns the new value to the
variable x.
# Example 1 def main(): x = int(input("Please enter an integer: ")) x += 5 print(x)
Unlike booleans, integers, floats, and strings, within a Python program, lists are mutable which means the value of a list can be changed. When a computer executes a line of code that adds, updates, or removes an element from a list, the computer doesn’t create a new list but instead changes the list. For example, line 4 in example 2 creates a list with two elements. Line 5 changes the list by adding the element "silk" to the list.
# Example 2 def main(): list1 = ["denim", "linen"] list1.append("silk") print(list1)
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 modify_args.py Python file and then open it in VS Code.
- Run the
modify_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 15, 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 change the value ofmain
’s local variable x?- Because x is a number and numbers in Python are immutable
- Because x is a list and lists in Python are mutable
- Why is the
modify_args
function able to change the value ofmain
’s local variable lx?- Because lx is a number and numbers in Python are immutable
- Because lx is a list and lists in Python are mutable
Sample Run
> python modify_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.