10 Chapter
10 Chapter
10.1 Lists
Survey
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
The following questions are part of a zyBooks survey to help us improve our content so
we can offer the best experience for students. The survey can be taken anonymously
and takes just 3-5 minutes. Please take a short moment to answer by clicking the
following link.
Link: Student survey
List basics
The list object type is one of the most important and often used types in a Python program. A list is a
container, which is an object that groups related objects together. A list is also a sequence; thus, the
contained objects maintain a left-to-right positional ordering. Elements of the list can be accessed via
indexing operations that specify the position of the desired element in the list. Each element in a list
can be a different type such as strings, integers, floats, or even other lists.
The animation below illustrates how a list is created using brackets [] around the list elements. The
animation also shows how a list object contains references to the contained objects.
PARTICIPATION
ACTIVITY
10.1.1:
Lists contain references to other objects.
Animation content:
undefined
Animation captions:
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
A list can also be created using the built-in list() function. The list() function accepts a single iterable
object argument, such as a string, list, or tuple, and returns a new list object. Ex: list('abc') creates a
new list with the elements ['a', 'b', 'c'].
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 1/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
An index is a zero-based integer matching to a specific position in the list's sequence of elements. A
programmer can reference a specific element in a list by providing an index. Ex: my_list[4] uses an
integer to access the element at index 4 (the 5th element) of my_list.
An index can also be an expression, as long as that expression evaluates into an integer. Replacing
the index with an integer variable, such as in my_list[i], allows©zyBooks
the programmer to quickly
01/03/22 22:13 and
1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
zyDE 10.1.1: List's ith element can be directly accessed using [i]: Oldest
people program.
Consider the following program that allows a user to print the age of
the Nth oldest known person to have ever lived. Note: The ages are in a
list sorted from oldest to youngest.
1. Modify the program to print the correct ordinal number ("1st", "2nd",
"3rd", "4th", "5th") instead of "1th", "2th", "3th", "4th", "5th".
2. For the oldest person, remove the ordinal number (1st) from the print
statement to say, "The oldest person lived 122 years".
Reminder: List indices begin at 0, not 1, thus the print statement uses
oldest_people[nth_person-1], to access the nth_person element
(element 1 at index 0, element 2 at index 1, etc.).
3
Load default template...
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 2/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
The program can quickly access the Nth oldest person's age using oldest_people[nth_person-1].
Note that the index is nth_person-1 rather than just nth_person because a list's indices start at 0, so
the first age is at index 0, the second at index 1, etc.
A list's index must be an integer type. The index cannot be a floating-point type, even if the value is 0.0,
1.0, etc.
ACTIVITY
10.1.2:
List indices. Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Given the following code, what is the output of each code segment?
print(animals[0])
1) print(animals[0])
2) print(animals[2])
3) print(animals[0 + 1])
4)
i = 3
print(animals[i])
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Modifying a list and common list operations
Unlike the string sequence type, a list is mutable and is thus able to grow and shrink without the
program having to replace the entire list with an updated copy. Such growing and shrinking capability
is called in-place modification. The highlighted lines in the list below indicate ways to perform an in-
place modification of the list:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 3/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Example
Operation Description Example code
output
my_list ©zyBooks
= [1, 2,01/03/22
3]
22:13 1172417
my_list = list('123')
['1',
list(iter) Creates a list. print(my_list)
'2', '3']
my_list[index] print(my_list[1])
2
a list.
my_list[start:end] print(my_list[1:3])
[2, 3]
another list's
elements.
place.
my_list.
The
my_list[len(my_list):] [1, 2, 3,
my_list[len(my_list):] = [x] append(x) method = [9]
9]
(explained in another print(my_list)
section) may be
preferred for clarity. ©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
my_list = [1, 2, 3]
Some of the operations in the table might be familiar to the reader because they are sequence type
operations also supported by strings. The dark-shaded rows highlight in-place modification
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 4/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
operations.
The below animation illustrates how a program can use in-place modifications to modify the contents
of a list.
PARTICIPATION
ACTIVITY
10.1.3:
In-place modification of a list.
LOUISVILLEMSBAPrep2DaviesWinter2022
1. A list, my_list, is created with the chars 'h', 'e', 'l', 'l', and 'o'.
2. Characters ' ', 'w', 'o', 'r', 'l', 'd', and '.' are added to the end of my_list.
3. Index 11 is changed to '!' character.
4. Element at index 5 is removed from my_list.
The difference between in-place modification of a list and an operation that creates an entirely new list
is important. In-place modification affects any variable that references the list, and thus can have
unintended side-effects. Consider the following code in which the variables your_teams and
my_teams reference the same list (via the assignment your_teams = my_teams). If either
your_teams or my_teams modifies an element of the list, then the change is reflected in the other
variable as well.
The below Python Tutor tool executes a Python program and visually shows the objects and variables
of a program. The tool shows names of variables on the left, with arrows connecting to bound objects
on the right. Note that the tool does not show each number or string character as unique objects to
improve clarity. The Python Tutor tool is available at www.pythontutor.com.
PARTICIPATION
ACTIVITY 10.1.4:
In-place modification of a list.
1 my_teams = ['Raptors', 'Heat', 'Nets']
2 your_teams = my_teams # Create a shared reference to same list
3
4 my_teams[1] = 'Lakers' # Modify list element
5
6 print('My teams are:', my_teams) # Both variables have changed
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
7 print('Your teams are:', your_teams) # Both variables have change
LOUISVILLEMSBAPrep2DaviesWinter2022
Frames Objects
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 5/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
In the above example, changing the elements of my_teams also affects the contents of your_teams.
The change occurs because my_teams and your_teams are bound to the same list object. The code
my_teams[1] = 'Lakers' modifies the element in position 1 of the shared list object, thus changing
the value of both my_teams[1] and your_teams[1].
The programmer of the above example probably meant to only change my_teams. The correct
©zyBooks 01/03/22 22:13 1172417
approach would have been to create a copy of the list instead. One simple method
Bharathi to create
Byreddy
a copy is
LOUISVILLEMSBAPrep2DaviesWinter2022
to use slice notation with no start or end indices, as in your_teams = my_teams[:].
PARTICIPATION
ACTIVITY
10.1.5:
In-place modification of a copy of a list.
1 my_teams = ['Raptors', 'Heat', 'Nets']
2 your_teams = my_teams[:] # Assign your_teams with a COPY of my_te
3
4 my_teams[1] = 'Lakers' # Modify list element
5
6 print('My teams are:', my_teams) # List element has changed
7 print('Your teams are:', your_teams) # List element has not chang
Frames Objects
On the other hand, assigning a variable with an element of an existing list, and then reassigning that
variable with a different value does not change the list.
PARTICIPATION
ACTIVITY
10.1.6:
List indexing.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
undefined
Animation captions:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 6/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
To change the value in the list above, the programmer would have to do an in-place modification
operation, such as colors[1] = 'orange'.
PARTICIPATION
ACTIVITY
10.1.7:
List basics.
Bharathi Byreddy
True LOUISVILLEMSBAPrep2DaviesWinter2022
False
CHALLENGE
ACTIVITY
10.1.1:
Enter the output for the list.
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
368708.2344834.qx3zqy7 LOUISVILLEMSBAPrep2DaviesWinter2022
Start
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 7/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
user_values = [2, 4, 7]
print(user_values)
1 2 3 4
Check Next
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY 10.1.2:
Modify a list.
Modify short_names by deleting the first element and changing the last element to Joe.
368708.2344834.qx3zqy7
1 user_input = input()
2 short_names = user_input.split()
3
4 ''' Your solution goes here '''
5
6 print(short_names)
LOUISVILLEMSBAPrep2DaviesWinter2022
A list method can perform a useful operation on a list such as adding or removing elements, sorting,
reversing, etc.
The table below shows the available list methods. Many of the methods perform in-place modification
of the list contents — a programmer should be aware that a method that modifies the list in-place
changes the underlying list object, and thus may affect the value©zyBooks
of a variable that 22:13
01/03/22 references the
1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
Final
List method Description Code example my_list
value
Adding elements
my_list = [5, 8]
[5, 8,
list.extend([x]) Add all items in [x] to list. 4, 12]
my_list.extend([4, 12])
Removing elements
Bharathi Byreddy
[5,
LOUISVILLEMSBAPrep2DaviesWinter2022
8]
my_list = [5, 8, 14]
val
is 5
Modifying elements
Bharathi
my_list = [14, 5, 8] Byreddy
[5,
8,
list.sort() Sort the items of list in-place. LOUISVILLEMSBAPrep2DaviesWinter2022
14]
my_list.sort()
Miscellaneous
Good practice is to use list methods to add and delete list elements, rather than alternative add/delete
approaches. Alternative approaches include syntax such as my_list[len(my_list):] = [val] to
add to a list, or del my_list[0] to remove from a list. Generally, using a list method yields more
readable code.
The list.sort() and list.reverse() methods rearrange a list element's ordering, performing in-place
modification of the list.
The list.index() and list.count() return information about the list and do not modify the list.
The below interactive tool shows a few of the list methods in action:
PARTICIPATION
©zyBooks 01/03/22 22:13 1172417
ACTIVITY 10.2.1:
In-place modification using list methods. Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Animation content:
undefined
Animation captions:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 10/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
The rider can enter a name to find the current position in line.
(Hint: Use the list.index() method.)
The rider can enter a name to remove the rider from the line.
1 riders_per_ride = 3 # Num riders per ride to dispatch
2
3 line = [] # The line of riders
4 num_vips = 0 # Track number of VIPs at front of line
5
6 menu = ('(1) Reserve place in line.\n' # Add rider to li
7 '(2) Reserve place in VIP line.\n' # Add VIP
8 '(3) Dispatch riders.\n' # Dispatch next ride
©zyBooks ca 22:13 1172417
01/03/22
9 '(4) Print riders.\n' Bharathi Byreddy
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 11/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Frank
1
Run
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY 10.2.2:
List methods.
temps.append(77)
print(temps[-1])
actors.insert(1, 'Affleck')
print(actors[0], actors[1],
actors[2])
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 12/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
ACTIVITY
10.2.1:
Reverse sort of list. Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
368708.2344834.qx3zqy7
1 user_input = input()
2 short_names = user_input.split()
3
4 ''' Your solution goes here '''
5
6 print(short_names)
Run
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 13/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
List iteration
A programmer commonly wants to access each element of a list. Thus, learning how to iterate
through a list using a loop is critical.
Looping through a sequence such as a list is so common that Python supports a construct called a
for loop, specifically for iteration purposes. The format of a for loop is shown below.
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
Each iteration of the loop creates a new variable by binding the next element of the list to the name
my_var. The loop body statements execute during each iteration and can use the current value of
my_var as necessary. 1
Programs commonly iterate through lists to determine some quantity about the list's items. Ex: The
following program determines the value of the maximum even number in a list:
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 14/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
nums = []
nums.append(int(token))
LOUISVILLEMSBAPrep2DaviesWinter2022
for index in range(len(nums)):
value = nums[index]
print(f'{index}: {value}')
max_num = None
max_num = num
elif (max_num != None) and (num > max_num ) and (num % 2 == 0):
max_num = num
0: 3
1: 5
2: 23
3: -1
4: 456
5: 1
6: 6
7: 83
....
0:-5
1:-10
2:-44
3:-2
4:-27
5:-9
6:-27
7:-9
Max even #: -2
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
If the user enters the numbers 7, -9, 55, 44, 20, -400, 0, 2, then the program will output
Max even #: 44. The code uses three for loops. The first loop converts the strings obtained from the
split() function into integers. The second loop prints each of the entered numbers. Note that the first
and second loops could easily be combined into a single loop, but the example uses two loops for
clarity. The third loop evaluates each of the list elements to find the maximum even number.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 15/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Before entering the first loop, the program creates the list nums as an empty list with the statement
nums = []. The program then appends items to the list inside the first loop. Omitting the initial empty
list creation would cause an error when the nums.append() function is called, because nums would
not actually exist yet.
The main idea of the code is to use a variable max_num to maintain the largest value seen so far as
the program iterates through the list. During each iteration, if the list's current element value is even
and larger than max_num so far, then the program assigns max_num ©zyBookswith01/03/22
current 22:13
value.1172417
Using a
variable to track a value while iterating over a list is very common behavior.Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
10.3.1:
Using a variable to keep track of a value while iterating over a list.
Animation content:
undefined
Animation captions:
A logic error in the above program would be to set max_even initially to 0, because 0 is not in fact the
largest value seen so far. This would result in incorrect output (of 0) if the user entered all negative
numbers. Instead, the program sets max_even to None.
PARTICIPATION
ACTIVITY 10.3.2:
List iteration.
for i in num:
©zyBooks 01/03/22 22:13 1172417
if i % 2 == 1:
Bharathi Byreddy
cnt_odd += 1
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 16/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
cnt_neg = 0
for i in num:
if i < 0:
for i in num:
if :
div_ten += 1
A common error is to try to access a list with an index that is out of the list's index range, e.g., to try to
access my_list[8] when my_list's valid indices are 0-7. Accessing an index that is out of range causes
the program to automatically abort execution and generate an IndexError. Ex: For a list my_list
containing 8 elements, the statement my_list[10] = 42 produces output similar to:
Iterating through a list for various purposes is an extremely important programming skill to master.
zyDE 10.3.1: Iterating through a list example: Finding the sum of a list's
elements.
Here is another example computing the sum of a list of integers. Note
that the code is somewhat different than the code computing the
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
max even value. For computing the sum, the program initializes a
LOUISVILLEMSBAPrep2DaviesWinter2022
variable sum to 0, then simply adds the current iteration's list element
value to that sum.
Run the program below and observe the output. Next, modify the
program to calculate the following:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 17/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
1 # User inputs string w/ n Bharathi Byreddy
The built-in enumerate() function iterates over a list and provides an iteration counter. The program
above uses the enumerate() function, which results in the variables pos and token being assigned the
current loop iteration element's index and value, respectively. Thus, the first iteration of the loop
assigns pos with 0 and token with the first user number; the second iteration assigns pos with 1 and
token with the second user number; and so on.
Iterating through a list to find or calculate certain values like the minimum/maximum or sum is so
common that Python provides built-in functions as shortcuts. Instead of writing a for loop and
tracking a maximum value, or adding a sum, a programmer can use a statement such as
max(my_list) or sum(my_list) to quickly obtain the desired value.
Bharathi Byreddy
Example
Function Description Example code
output
False
(!= 0), or if the list is empty. print(all([0, 1, 2]))
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 18/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
any(list) False
True. print(any([0, 0]))
LOUISVILLEMSBAPrep2DaviesWinter2022
Get the sum of all elements in the
sum(list) print(sum([-3, 5, 25])) 27
list.
1
2 #Lebron James: Statistics
3 games_played = [79, 80, 79
4 points = [1654, 2175, 2478
5 assists = [460, 636, 814,
6 rebounds = [432, 588, 556,
7
8 # Print total points
9
©zyBooks 01/03/22 22:13 1172417
11
LOUISVILLEMSBAPrep2DaviesWinter2022
12 # Print best scoring years
13
14 # Print worst scoring year
15
16
17
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 19/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
PARTICIPATION
ACTIVITY
10.3.3:
Lists and built-in functions.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Check Show answer
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY
10.3.1:
Get user guesses.
Write a loop to populate the list user_guesses with a number of guesses. The variable
num_guesses is the number of guesses the user will have, which is read first as an integer.
Read each guess (an integer) one at a time using int(input()).
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 20/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
3952
user_guesses: [9, 5, 2]
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
368708.2344834.qx3zqy7 LOUISVILLEMSBAPrep2DaviesWinter2022
1 num_guesses = int(input())
2 user_guesses = []
3
4 ''' Your solution goes here '''
5
6 print('user_guesses:', user_guesses)
Run
CHALLENGE
ACTIVITY 10.3.2:
Sum extra credit.
Assign sum_extra with the total extra credit received given list test_grades. Iterate through
the list with for grade in test_grades:. The code uses the Python split() method to split
a string at each space into a list of string values and the map() function to convert each
string value to an integer. Full credit is 100, so anything over 100 is extra credit.
Sample output for the given program with input: '101 83 107 90'
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
Sum extra: 8
LOUISVILLEMSBAPrep2DaviesWinter2022
(because 1 + 0 + 7 + 0 is 8)
368708.2344834.qx3zqy7
1 user_input = input()
2 test_grades = list(map(int, user_input.split())) # test_grades is an integer list of
3
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 21/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
4
5 sum_extra = 0 # Initialize 0 before your loop
6
7 ''' Your solution goes here '''
8
9 print('Sum extra:', sum_extra)
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Run
CHALLENGE
ACTIVITY
10.3.3:
Hourly temperature reporting.
Write a loop to print all elements in hourly_temperature. Separate elements with a ->
surrounded by spaces.
Sample output for the given program with input: '90 92 94 95'
368708.2344834.qx3zqy7
1 user_input = input()
2 hourly_temperature = user_input.split()
3
4 ''' Your solution goes here '''
5
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Run
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 22/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
(*1) Actually, a for loop works on any iterable object. An iterable object is any object that can access
each of its elements one at a time -- most sequences like lists, strings, and tuples are iterables. Thus,
for loops are not specific to lists.
LOUISVILLEMSBAPrep2DaviesWinter2022
The following activities can help one become comfortable with iterating through lists. Challenge
yourself with these list games.
PARTICIPATION
ACTIVITY
10.4.1:
Find the maximum value in the list.
If a new maximum value is seen, then click 'Store value'. Try again to get your best time.
Start
max
X X X X X X X
PARTICIPATION
ACTIVITY
10.4.2:
Negative value counting in list.
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
If a negative value is seen, then click 'Increment'. Try again to get your best time.
Start
Counter
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 23/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
X X X X X X X 0
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY 10.4.3:
Manually sorting largest value.
Move the largest value to the right-most position of the list. If the larger of the two current
values is on the left, then swap the values. Try again to get your best time.
Start
X X X X X X X
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 24/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
The program accesses elements of a nested list using syntax such as my_list[0][0].
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
10.5.1:
List nesting.
Animation captions:
PARTICIPATION
ACTIVITY 10.5.2:
List nesting.
3) Given the list nums = [[10, 20, 30], ©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
temperatures, etc. List nesting allows for a programmer to also create a multi-dimensional data
structure, the simplest being a two-dimensional table, like a spreadsheet or tic-tac-toe board. The
following code defines a two-dimensional table using nested lists:
tic_tac_toe = [
X O X
]
X
O O X
print(tic_tac_toe[0][0], tic_tac_toe[0][1], tic_tac_toe[0][2])
The example above creates a variable tic_tac_toe that represents a 2-dimensional table with 3 rows
and 3 columns, for 3*3=9 total table entries. Each row in the table is a nested list. Table entries can be
accessed by specifying the desired row and column: tic_tac_toe [1][1] accesses the middle square in
row 1, column 1 (starting from 0), which has a value of 'X'. The following animation illustrates:
PARTICIPATION
ACTIVITY 10.5.3:
Two-dimensional list.
Animation captions:
©zyBooks 01/03/22 22:13 1172417
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 26/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Run the following program, entering the text '1 2' as input to find the
distance between LA and Chicago. Try other pairs. Next, try modifying
the program by adding a new city, Anchorage, that is 3400, 3571, and
4551 miles from Los Angeles, Chicago, and Boston, respectively.
©zyBooks 01/03/22 22:13 1172417
Note that the styling of the nested list in this example makesBharathi
use of Byreddy
12
Load default template...
1 # direct driving distances
2 # 0: Boston 1: Chicago Run
3
4 distances = [
5 [
6 0,
7 960, # Boston-Chi
8 2960 # Boston-Los
9 ],
10 [
11 960, # Chicago-Bo
12 0,
13 2011 # Chicago-Lo
14 ],
15 [
16 2960, # Los Angel
17 2011, # Los-Angel
The level of nested lists is arbitrary. A programmer might create a three-dimensional list structure as
follows:
nested_table = [
©zyBooks 01/03/22 22:13 1172417
[
Bharathi Byreddy
[10, 0, 55],
LOUISVILLEMSBAPrep2DaviesWinter2022
[0, 4, 16]
],
[0, 0, 1],
[1, 20, 2]
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 27/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
A number from the above three-dimensional list could be accessed using three indexing operations,
as in nested_table[1][1][1].
PARTICIPATION
ACTIVITY
10.5.4:
Multi-dimensional lists.
scores = [
Bharathi Byreddy
[75, LOUISVILLEMSBAPrep2DaviesWinter2022
100, 82, 76],
As always with lists, a typical task is to iterate through the list elements. A programmer can access all
of the elements of nested lists by using nested for loops. The first for loop iterates through the
elements of the outer list (rows of a table), while the nested loop iterates through the inner list
elements (columns of a table). The code below defines a 3x3 table and iterates through each of the
table entries:
PARTICIPATION
ACTIVITY
10.5.5:
Iterating over multi-dimensional lists.
LOUISVILLEMSBAPrep2DaviesWinter2022
undefined
Animation captions:
1. Each iteration row is assigned the next list element from currency. Each item in a row is
printed in the inner loop.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 28/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
The outer loop assigns the variable row with one of the list elements. The inner loop then iterates over
the elements in that list. Ex: On the first iteration of the outer loop row is [1, 5, 10]. The inner loop then
assigns cell 1 on the first iteration, 5 on the second iteration, and 10 on the last iteration.
Combining nested for loops with the enumerate() function gives easy access to the current row and
column:
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
currency[0][0] is
1.00
currency[0][1] is
5.00
currency = [
currency[0][2] is
[1, 5, 10 ], # US Dollars
10.00
]
currency[1][1] is
for row_index, row in enumerate(currency):
3.77
currency[1][2] is
for column_index, item in enumerate(row):
7.53
print(f'currency[{row_index}][{column_index}] is currency[2][0] is
{item:.2f}')
0.65
currency[2][1] is
3.25
currency[2][2] is
6.50
PARTICIPATION
ACTIVITY 10.5.6:
Find the error.
The desired output and actual output of each program is given. Find the error in each
program.
1) 0 2 4 6
Desired output:
0 3 6 9 12
nums = [
Bharathi Byreddy
[0, 2, 4, 6],
LOUISVILLEMSBAPrep2DaviesWinter2022
[0, 3, 6, 9, 12]
for n1
in nums
for n2
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 29/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
in nums
print()
tictactoe = [
Bharathi Byreddy
num_X_in_row = 0
if square == 'X'
num_X_in_row += 1
if num_X_in_row == square
print('X wins!')
break
else:
print("Cat's game!")
CHALLENGE
ACTIVITY 10.5.1:
Print multiplication table.
Print the two-dimensional list mult_table by row and column. On each line, each character is
separated by a space. Hint: Use nested loops.
1 | 2 | 3
2 | 4 | 6
Bharathi Byreddy
3 | 6 | 9
LOUISVILLEMSBAPrep2DaviesWinter2022
368708.2344834.qx3zqy7
1 user_input= input()
2 lines = user_input.split(',')
3
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 30/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
3
4 # This line uses a construct called a list comprehension, introduced elsewhere,
5 # to convert the input string into a two-dimensional list.
6 # Ex: 1 2, 2 4 is converted to [ [1, 2], [2, 4] ]
7
8 mult_table = [[int(num) for num in line.split()] for line in lines]
9
10 ''' Your solution goes here '''
11
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Run
The slice boston_bruins[0:2] produces a new list containing the elements in positions 0 and 1:
Bharathi Byreddy
['Tyler', 'Zdeno']. The end position is not included in the produced list – to include the final element of a
LOUISVILLEMSBAPrep2DaviesWinter2022
list in a slice, specify an end position past the end of the list. Ex: boston_bruins[1:3] produces the
list ['Zdeno', 'Patrice'].
PARTICIPATION
ACTIVITY
10.6.1:
List slicing.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 31/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Animation captions:
Negative indices can also be used to count backwards from the ©zyBooks
end of the01/03/22
list. 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
three
[1992, 1996]
A position of -1 refers to the last element of the list, thus election_years[0:-1] creates a slice containing
all but the last election year. Such usage of negative indices is especially useful when the length of a
list is not known, and is simpler than the equivalent expression election_years[0:len(election_years)-1].
PARTICIPATION
ACTIVITY
10.6.2:
List slicing.
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 32/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
An optional component of slice notation is the stride, which indicates how many elements are skipped
between extracted items in the source list. Ex: The expression my_list[0:5:2] has a stride of 2, thus
skipping every other element, and resulting in a slice that contains the elements in positions 0, 2, and
4. The default stride value is 1 (the expressions my_list[0:5:1] and©zyBooks
my_list[0:5] being22:13
01/03/22 equivalent).
1172417
Bharathi Byreddy
If the reader has studied string slicing, then list slicing shouldLOUISVILLEMSBAPrep2DaviesWinter2022
be familiar. In fact, slicing has the same
semantics for most sequence type objects.
PARTICIPATION
ACTIVITY 10.6.3:
List slicing.
A table of common list slicing operations are given below. Note that omission of the start or end
positions, such as my_list[:2] or my_list[4:], has the same meaning as in string slicing. my_list[:2]
includes every element up to position 2. my_list[4:] includes every element following position 4
(including the element at position 4).
Bharathi Byreddy
Example
LOUISVILLEMSBAPrep2DaviesWinter2022
Operation Description Example code
output
Get a list
from start to my_list = [5, 10, 20]
[5,
my_list[start:end] 10]
end (minus print(my_list[0:2])
1).
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 33/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Get a list
©zyBooks 01/03/22 22:13[20,
from start to my_list = [5, 10, 20, 40, 80]
1172417
Get a list
from [5,
my_list = [5, 10, 20, 40, 80]
10,
my_list[:end] beginning of 20,
print(my_list[:4])
list to end 40]
(minus 1).
[5,
Get a copy of my_list = [5, 10, 20, 40, 80]
10,
my_list[:] 20,
the list. print(my_list[:]) 40,
80]
The interpreter handles incorrect or invalid start and end positions in slice notation gracefully. An end
position that exceeds the length of the list is treated as the end of the list. If the end position is less
than the start position, an empty list is produced.
PARTICIPATION
ACTIVITY
10.6.4:
Match the expressions to the list.
Match the expression on the left to the resulting list on the right. Assume that my_list is the
following Fibonacci sequence:
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
my_list[2:5] my_list[4:]
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 34/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
[]
[1, 1, 2, 3, 5, 8, 13, 21, 34]
[5]
[2, 3, 5]
©zyBooks 01/03/22 22:13 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
Reset
CHALLENGE
ACTIVITY 10.6.1:
List slicing.
368708.2344834.qx3zqy7
Start
new_list = my_list[0:4]
print(new_list)
1 2 3 4
Check Next
LOUISVILLEMSBAPrep2DaviesWinter2022
Sometimes a program iterates over a list while modifying the elements, such as by changing some
elements' values, or by moving elements' positions.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 35/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
The below example of changing element's values combines the len() and range() functions to iterate
over a list and increment each element of the list by 5.
LOUISVILLEMSBAPrep2DaviesWinter2022
for i in range(len(my_list)):
my_list[ i ] += 5
The figure below shows two programs that each attempt to convert any negative numbers in a list to
0. The program on the right is incorrect, demonstrating a common logic error.
tokens = user_input.split()
nums = []
nums.append(int(token))
print()
print(f'{pos}: {val}')
if num < 0:
©zyBooks 01/03/22 22:13 1172417
Bharathi
num = 0 # Logic error: Byreddy
temp
LOUISVILLEMSBAPrep2DaviesWinter2022
variable num set to 0
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 36/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
numbers: ')
0: 5
1: 67
2: -5
tokens =
3: -4
user_input.split()
4: 5
5: 6
# Convert strings to 6: 6
integers
7: 4
nums = []
New numbers:
Bharathi Byreddy
nums.append(int(token))
LOUISVILLEMSBAPrep2DaviesWinter2022
print()
print(f'{pos}: {val}')
for pos in
range(len(nums)):
if nums[pos] < 0:
nums[pos] = 0
Enter numbers:5 67 -5 -4 5 6 6
4
0: 5
1: 67
2: -5
3: -4
4: 5
5: 6
6: 6
7: 4
New numbers:
5 67 0 0 5 6 6 4
Bharathi Byreddy
The program on the right illustrates a common logic error. A common error when modifying a list
LOUISVILLEMSBAPrep2DaviesWinter2022
during iteration is to update the loop variable instead of the list object. The statement num = 0 simply
binds the name num to the integer literal value 0. The reference in the list is never changed.
In contrast, the program on the left correctly uses an index operation nums[pos] = 0 to modify to 0
the reference held by the list in position pos. The below activities demonstrate further; note that only
the second program changes the list's values.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 37/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
PARTICIPATION
ACTIVITY
10.7.1:
Incorrect list modification example.
1 nums = [50, 10, -5, -4, 6]
2 for n in nums:
3 if n < 0:
4 n = 0 ©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
<< First < Back Step 1 of 14 Forward > Last >
Frames Objects
PARTICIPATION
ACTIVITY
10.7.2:
Corrected list modification example.
1 nums = [50, 10, -5, -4, 6]
2 for n in range(len(nums)):
3 if nums[n] < 0:
4 nums[n] = 0
Frames Objects
CHALLENGE
ACTIVITY
10.7.1:
Iterating through a list using range().
Bharathi Byreddy
Start LOUISVILLEMSBAPrep2DaviesWinter2022
user_values = [3, 6, 7]
print(user_values[pos])
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 38/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
1 2 3 4
Check Next
PARTICIPATION
©zyBooks 01/03/22 22:13 1172417
ACTIVITY 10.7.3:
List modification. Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
tmp = nums[pos] / 2
if (tmp % 2) == 0:
nums[pos] = tmp
A common error is to add or remove a list element while iterating over that list. Such list modification
can lead to unexpected behavior if the programmer is not careful. Ex: Consider the following program
that reads in two sets of numbers and attempts to find numbers in the first set that are not in the
second set.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 39/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
nums1 = []
Enter first set of numbers:5 10
nums2 = []
15 20
0: 5
1: 10
')
3: 20
0: 15
print()
©zyBooks 01/03/22 22:13 1172417
2: 25
3: 30
Bharathi Byreddy
nums1.append(int(val))
LOUISVILLEMSBAPrep2DaviesWinter2022
Deleting 15
print(f'{pos}: {val}')
Numbers only in first set: 5 10
20
user_input = input('Enter second set of
numbers:')
tokens = user_input.split()
print()
nums2.append(int(val))
print(f'{pos}: {val}')
print()
if val in nums2:
print(f'Deleting {val}')
nums1.remove(val)
The above example iterates over the list nums1, deleting an element from the list if the element is also
found in the list nums2. The programmer expected a certain result, namely that after removing an
element from the list, the next iteration of the loop would reference the next element as normal.
However, removing the element shifts the position of each following element in the list to the left by
©zyBooks 01/03/22 22:13 1172417
one. In the example above, removing 15 from nums1 shifts the value 20Bharathi
left intoByreddy
position
2. The loop,
LOUISVILLEMSBAPrep2DaviesWinter2022
having just iterated over position 2 and removing 15, moves to the next position and finds the end of
the list, thus never evaluating the final value 20.
The problem illustrated by the example above has a simple fix: Iterate over a copy of the list instead of
the actual list being modified. Copying the list allows a programmer to modify, swap, add, or delete
elements without affecting the loop iterations. The easiest way to copy the iterating list is to use slice
notation inside of the loop expression, as in:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 40/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
# Loop statements.
Bharathi Byreddy
PARTICIPATION LOUISVILLEMSBAPrep2DaviesWinter2022
ACTIVITY
10.7.4:
List modification.
Animation captions:
1. The loop, having just iterated over position 1 and removing 10, moves to the next position and
finds the end of the list, thus never evaluating the final value 15.
2. The problem illustrated by the example above can be fixed by iterating over a copy of the list
instead of the actual list being modified.
PARTICIPATION
ACTIVITY
10.7.5:
Modifying a list while iterating.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 41/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
LOUISVILLEMSBAPrep2DaviesWinter2022
list.
True
False
A programmer commonly wants to modify every element of a list in the same way, such as adding 10
to every element. The Python language provides a convenient construct, known as list
comprehension, that iterates over a list, modifies each element, and returns a new list consisting of
the modified elements.
A list comprehension construct has the following form:
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
1. An expression component to evaluate for each element in the iterable object.
2. A loop variable component to bind to the current iteration element.
3. An iterable object component to iterate over (list, string, tuple, enumerate, etc).
A list comprehension is always surrounded by brackets, which is a helpful reminder that the
comprehension builds and returns a new list object. The loop variable and iterable object components
make up a normal for loop expression. The for loop iterates through the iterable object as normal, and
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 42/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
the expression operates on the loop variable in each iteration. The result is a new list containing the
values modified by the expression. The below program demonstrates a simple list comprehension
that increments each value in a list by 5.
Bharathi Byreddy
New list contains: [15, 25, 35]
print('New list contains:', list_plus_5)
PARTICIPATION
ACTIVITY 10.8.1:
List comprehension.
Animation captions:
Programmers commonly prefer using a list comprehension rather than a for loop in many situations.
Such preference is due to less code and due to more-efficient execution by the interpreter. The table
below shows various for loops and equivalent list comprehensions.
Equivalent list
Num Description For loop Output of both programs
comprehension
my_list = [5,
my_list = [5, 20, 50]
©zyBooks 01/03/22 22:13 1172417
my_list =
1 every range(len(my_list)):
LOUISVILLEMSBAPrep2DaviesWinter2022
[15, 30, 60]
[(i+10) for i
my_list[ i ] += 10
element. in my_list]
print(my_list)
print(my_list)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 43/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
range(len(my_list)):
my_list =
my_list[ i ] = [str(i) for i
str(my_list[ i ])
in my_list]
print(my_list)
print(my_list)
Convert numbers:')
input('Enter
Bharathi Byreddy
my_list = []
numbers:')
print(my_list)
print(my_list)
print(sum_list)
print(sum_list)
list.
Find the
my_list = [[5, 10, 15], my_list = [[5,
sum of the
[2, 3, 16], [100]]
10, 15], [2, 3,
row with the sum_list = []
16], [100]]
dimensional print(min_row)
print(min_row)
table.
Note that list comprehension is not an exact replacement of for loops, because list comprehensions
create a new list object, whereas the typical for loop is able to modify an existing list.
The third row of the table above has an expression in place of the iterable object component of the list
comprehension, inp.split(). That expression is evaluated first, and the list comprehension will loop
©zyBooks 01/03/22 22:13 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
The last example from above is interesting because the list comprehension is wrapped by the built-in
function min(). List comprehension builds a new list when evaluated, so using the new list as an
argument to min() is allowed – conceptually the interpreter is just evaluating the more familiar code:
min([30, 21, 100]).
PARTICIPATION
ACTIVITY
10.8.2:
List comprehension examples.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 44/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
LOUISVILLEMSBAPrep2DaviesWinter2022
2) Alter the list comprehension from
row 2 to convert each number to a
float instead of a string.
my_list = [5, 20, 50]
my_list = [
for i in
my_list]
print(my_list)
LOUISVILLEMSBAPrep2DaviesWinter2022
number contained by my_list.
my_list = [[5, 10, 15], [2, 3,
16], [100]]
sum_list =
([sum(row)
for row in my_list])
print(sum_list)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 45/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
PARTICIPATION
ACTIVITY
10.8.3:
Building list comprehensions.
Write a list comprehension that contains elements with the desired values.
©zyBooks Use the
01/03/22 name
22:13 'i'
1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
A list comprehension can be extended with an optional conditional clause that causes the statement
©zyBooks 01/03/22 22:13 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 46/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Using the above syntax will only add an element to the resulting list if the condition evaluates to True.
The following program demonstrates list comprehension with a conditional clause that returns a list
with only even numbers.
Bharathi Byreddy
numbers:').split()]
Even numbers only: [52, 16]
....
PARTICIPATION
ACTIVITY 10.8.4:
Building list comprehensions with conditions.
Write a list comprehension that contains elements with the desired values. Use the name 'i'
as the loop variable. Use parentheses around the expression or condition as necessary.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY
10.8.1:
List comprehensions.
368708.2344834.qx3zqy7
Start
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 47/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
my_list = [-1, 0, 1, 2]
print(new_list)
1 2 3
LOUISVILLEMSBAPrep2DaviesWinter2022
One of the most useful list methods is sort(), which performs an in-place rearranging of the list
elements, sorting the elements from lowest to highest. The normal relational equality rules are
followed: numbers compare their values, strings compare ASCII/Unicode encoded values, lists
compare element-by-element, etc. The following animation illustrates.
PARTICIPATION
ACTIVITY
10.9.1:
Sorting a list using list.sort().
Animation captions:
The sort() method performs element-by-element comparison to determine the final ordering. Numeric
type elements like int and float have their values directly compared to determine relative ordering, i.e.,
5 is less than 10. ©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
The below program illustrates the basic usage of the list.sort() method, reading book titles into a list
and sorting the list alphabetically.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 48/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
books = []
user_input = input(prompt).strip()
Enter new book: Pride, Prejudice, and Zombies
Enter new book: Programming in Python
books.append(user_input)
Enter new book: exit
user_input = input(prompt).strip()
Alphabetical order:
books.sort()
Hackers and ©zyBooks
Painters
01/03/22 22:13 1172417
Pride, Prejudice, and Zombies
Bharathi Byreddy
print('\nAlphabetical order:')
Programming in Python
LOUISVILLEMSBAPrep2DaviesWinter2022
World War Z
for book in books:
print(book)
The sort() method performs in-place modification of a list. Following execution of the statement
my_list.sort(), the contents of my_list are rearranged. The sorted() built-in function provides the same
sorting functionality as the list.sort() method, however, sorted() creates and returns a new list instead
of modifying an existing list.
Figure 10.9.2: Using sorted() to create a new sorted list from an existing
list without modifying the existing list.
Original numbers: [-5, 5, -100,
sorted_numbers = sorted(numbers)
23, 4, 5]
Sorted numbers: [-100, -5, 4, 5,
print('\nOriginal numbers:', numbers)
5, 23]
print('Sorted numbers:', sorted_numbers)
ACTIVITY
10.9.2:
list.sort() and sorted(). LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 49/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
primes.sort()
print(primes)
True
False
©zyBooks 01/03/22 22:13 1172417
True
False
Both the list.sort() method and the built-in sorted() function have an optional key argument. The key
specifies a function to be applied to each element prior to being compared. Examples of key functions
are the string methods str.lower, str.upper, or str.capitalize.
Consider the following example, in which a roster of names is sorted alphabetically. If a name is
mistakenly uncapitalized, then the sort algorithm places the name at the end of the list, because
lower-case letters have a larger encoded value than upper-case letters. Ex: 'a' maps to the ASCII
decimal value of 97 and 'A' maps to 65. Specifying the key function as str.lower (note the absence of
parentheses) automatically converts the elements to lower-case before comparison, thus placing the
lower-case name at the appropriate position in the sorted list.
names = []
user_input = input(prompt)
names.append(user_input)
user_input = input(prompt)
no_key_sort = sorted(names)
©zyBooks 01/03/22 22:13 1172417
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 50/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Sorting without key: ['Serena Williams', 'Venus Williams', 'john McEnroe', 'rafael Nadal']
Sorting with key: ['john McEnroe', 'rafael Nadal', 'Serena Williams', 'Venus Williams']
Bharathi Byreddy
The key argument can be assigned any function, not just string methods like str.upper and str.lower.
LOUISVILLEMSBAPrep2DaviesWinter2022
Ex: A programmer might want to sort a two-dimensional list by the max of the rows, which can be
accomplished by assigning key with the built-in function max, as in: sorted(x, key=max).
Sorting also supports the reverse argument. The reverse argument can be set to a Boolean value,
either True or False. Setting reverse=True flips the sorting from lower-to-highest to highest-to-lowest.
Thus, the statement sorted([15, 20, 25], reverse=True) produces a list with the elements [25,
20, 15].
PARTICIPATION
ACTIVITY 10.9.3:
Sorting.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 51/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Command-line arguments are values entered by a user when running a program from a command
line. A command line exists in some program execution environments, wherein a user can run a
program by typing at a command prompt. Ex: To run a Python program named "myprog.py" with an
argument specifying the location of a file named "myfile1.txt", the user would enter the following at the
command prompt:
The contents of this command line are automatically stored in the list sys.argv, which is stored in the
standard library sys module. sys.argv consists of one string element for each argument typed on the
command line.
When executing a program, the interpreter parses the entire command line to find all sequences of
characters separated by whitespace, storing each as a string within list variable argv. As the entire
command line is passed to the program, the name of the program executable is always added as the
first element of the list. Ex: For a command line of python myprog.py myfile1.txt, argv has the
contents ['myprog.py', 'myfile1.txt'].
The following animation further illustrates.
PARTICIPATION
ACTIVITY 10.10.1:
Command-line arguments.
Bharathi Byreddy
The following program illustrates simple use of command-line arguments, where the program name is
myprog, and two additional arguments should be passed to the program.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 52/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Hello Tricia.
import sys
12 is a great age.
©zyBooks
> python myprog.py 01/03/22
Aisha 30
22:13 1172417
name = sys.argv[1]
Hello Aisha.
Bharathi Byreddy
age = int(sys.argv[2])
30 is a LOUISVILLEMSBAPrep2DaviesWinter2022
great age.
print(f'Hello {name}.')
> python myprog.py Franco
age = sys.argv[2]
While a program may expect the user to enter certain command-line arguments, there is no guarantee
that the user will do so. A common error is to access elements within argv without first checking the
length of argv to ensure that the user entered enough arguments, resulting in an IndexError being
generated. In the last example above, the user did not enter the age argument, resulting in an
IndexError when accessing argv. Conversely, if a user entered too many arguments, extra arguments
will be ignored. Above, if the user typed python myprog.py Alan 70 pizza, "pizza" will be stored in
argv[3] but will never be used by the program.
Thus, when a program uses command-line arguments, a good practice is to always check the length
of argv at the beginning of the program to ensure that the user entered the correct number of
arguments. The following program uses the statement if len(sys.argv) != 3 to check for the
correct number of arguments, the three arguments being the program, name, and age. If the number
of arguments is incorrect, the program prints an error message, referred to as a usage message, that
provides the user with an example of the correct command-line argument format. A good practice is
to always output a usage message when the user enters incorrect command-line arguments.
import sys
12
if len(sys.argv) != 3:
Hello Tricia.Byreddy
12 is a
error with 1.
> python myprog.py Franco
Usage: python myprog.py
name = sys.argv[1]
name age
age = int(sys.argv[2])
> python myprog.py Alan 70
pizza
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 53/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Note that all command-line arguments in argv are strings. If an argument represents a different type
like a number, then the argument needs to be converted using one of the built-in functions such as
int() or float().
A single command-line argument may need to include a space. Ex: A person's name might be "Mary
Jane". Recall that whitespace characters are used to separate the©zyBooks 01/03/22
character typed 22:13
on the1172417
command
Bharathi Byreddy
line into the arguments for the program. If the user provided LOUISVILLEMSBAPrep2DaviesWinter2022
a command line of
python myprog.py Mary Jane 65, the command-line arguments would consist of four arguments:
"myprog.py", "Mary", "Jane", and "65". When a single argument needs to contain a space, the user can
enclose the argument within quotes "" on the command line, such as the following, which will result in
only 3 command-line arguments, where sys.argv has the contents ['myprog.py', 'Mary Jane', '65'].
PARTICIPATION
ACTIVITY 10.10.2:
Command-line arguments.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Exploring further:
Command-line arguments can become quite complicated for large programs with many options.
There are entire modules of the standard library dedicated to aiding a programmer develop
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 54/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
sophisticated argument parsing strategies. The reader is encouraged to explore modules such as
argparse and getopt.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
The following is a sample programming lab activity; not all classes using a zyBook require students to
fully complete this activity. No auto-checking is performed. Users planning to fully complete this
program may consider first developing their code in a separate programming environment.
A list can be useful in solving various engineering problems. One problem is computing the voltage
drop across a series of resistors. If the total voltage across the resistors is V, then the current through
the resistors will be I = V/R, where R is the sum of the resistances. The voltage drop Vx across resistor
x is then Vx = I · Rx.
Modify the program to compute the voltage drop across each resistor,
store each in another list voltage_drop, and finally print the results in
the following format:
1) 3.3
2) 1.5
©zyBooks 01/03/22 22:13 1172417
3) 2.0
Bharathi Byreddy
4) 4.0
LOUISVILLEMSBAPrep2DaviesWinter2022
5) 2.2
1) 3.0 V
2) 1.4 V
3) 1.8 V
4) 3.7 V
5) 2.0 V
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 55/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
1 num_resistors = 5
2 resistors = []
3 voltage_drop = []
4
5
6 print(f'{num_resistors} resistors are in the series.')
7 print('This program calculates the'),
8 print('voltage drop across each resistor.')
9 ©zyBooks 01/03/22 22:13 1172417
10 Bharathi
input_voltage = float(input('Input voltage applied to cirByreddy
12
3.3
1.5
2
Run
Engineering problems commonly involve matrix representation and manipulation. A matrix can be
captured using a two-dimensional list. Then matrix operations can be defined on such lists.
Run the program below. Try changing the size and value of the
matrices and computing new values.
Bharathi Byreddy
1 m1_rows = 4 LOUISVILLEMSBAPrep2DaviesWinter2022
2 m1_cols = 2
3 m2_rows = m1_cols # Must have same value
4 m2_cols = 3
5
6 m1 = [
7 [3, 4],
8 [2, 3],
9 [1, 2],
10 [0, 2]
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 56/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
10 [0, 2]
11 ]
12
13 m2 = [
14 [5, 4, 4],
15 [0, 2, 3]
16 ]
17
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
10.12 Dictionaries
A dictionary is another type of container object that is different from sequences like strings, tuples,
and lists. Dictionaries contain references to objects as key-value pairs – each key in the dictionary is
associated with a value, much like each word in an English language dictionary is associated with a
definition. As of Python 3.7, dictionary elements maintain their insertion order. The dict type
implements a dictionary in Python.
PARTICIPATION
ACTIVITY
10.12.1:
Dictionaries.
Animation captions:
The first approach wraps braces { } around key-value pairs of literals and/or variables:
{'Jose': 'A+', 'Gino': 'C-'} creates a dictionary with two keys 'Jose' and 'Gino' that are
associated with the grades 'A+' and 'C-', respectively. ©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 57/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
In practice, a programmer first creates a dictionary and then adds entries, perhaps by reading user-
input or text from a file. Dictionaries are mutable, thus entries can be added, modified, or removed in-
place. The table below shows some common dict operations.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
del
Deletes the key from a dict. del my_dict['Jose']
my_dict[key]
key in
Tests for existence of key in my_dict. if 'Jose' in my_dict:
# ....
my_dict
Dictionaries can contain objects of arbitrary type, even other containers such as lists and nested
dictionaries. Ex: my_dict['Jason'] = ['B+', 'A-'] creates an entry in my dict whose value is a
list containing the grades of the student 'Jason'.
Pre-enter any©zyBooks
input for 01/03/22
program,22:13 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
1
2 student_grades = {} # Cre
Run
3 grade_prompt = "Enter name
4 menu_prompt = ("1. Add/mod
5 "2. Delete
6 "3. Print
7 "4. Quit\n
8
9 while True: # Exit when u
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 58/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
9 while True: # Exit when u
10 command = input(menu_p
11 if command == '1':
12 name, grade = inpu
13 # Your code here
14 elif command == '2':
15 # Your code here
16 elif command == '3':
17 # Your code here
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
10.12.2:
Dictionaries.
my_dict = dict(name='Bob',
grade='A+')
True
False
CHALLENGE
ACTIVITY 10.12.1:
Delete from dictionary.
368708.2344834.qx3zqy7
1 user_input = input()
2 entries = user_input.split(',')
3 t it l {}
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 59/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
3 country_capital = {}
4
5 for pair in entries:
6 split_pair = pair.split(':')
7 country_capital[split_pair[0]] = split_pair[1]
8 # country_capital is a dictionary, Ex. { 'Germany': 'Berlin', 'France': 'Pari
9
10 ''' Your solution goes here '''
11
12 print('Prussia deleted?', end=' ') ©zyBooks 01/03/22 22:13 1172417
14 print('No.') LOUISVILLEMSBAPrep2DaviesWinter2022
15 else:
16 print('Yes.')
17
Run
CHALLENGE
ACTIVITY 10.12.2:
Enter the output of dictionaries.
368708.2344834.qx3zqy7
Start
airport_codes = {}
airport_codes['Cincinnati'] = 'CVG'
print(airport_codes['San Francisco'])
print(airport_codes['Cincinnati'])
1 2 3
Check Next
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 60/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
LOUISVILLEMSBAPrep2DaviesWinter2022
all items
my_dict.clear() my_dict.clear()
{}
from the
print(my_dict)
dictionary.
Reads the
value of
the key
from the
dictionary.
my_dict = {'Ahmad': 1, 'Jane': 42}
If the key 42
Merges
dictionary
my_dict1
with
another
dictionary
my_dict2. {'Ahmad':
my_dict = {'Ahmad': 1, 'Jane': 42}
1,
Existing 'Jane':
my_dict1.update(my_dict2) my_dict.update({'John': 50})
42,
entries in
print(my_dict) 'John':
my_dict1 50}
are ©zyBooks 01/03/22 22:13 1172417
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 61/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
returned. LOUISVILLEMSBAPrep2DaviesWinter2022
Modification of dictionary elements using the above methods is performed in-place. Ex: Following the
evaluation of the statement my_dict.pop('Ahmad'), any other variables that reference the same object
as my_dict will also reflect the removal of 'Ahmad'. As with lists, a programmer should be careful not
to modify dictionaries without realizing that other references to the objects may be affected.
PARTICIPATION
ACTIVITY
10.13.1:
Dictionary methods.
Determine the output of each code segment. If the code produces an error, type None.
Assume that my_dict has the following entries:
my_dict = dict(bananas=1.59, fries=2.39, burger=3.50, sandwich=2.99)
1) my_dict.update(dict(soda=1.49,
burger=3.69))
burger_price =
my_dict.get('burger', 0)
print(burger_price)
2) my_dict['burger'] =
my_dict['sandwich']
val = my_dict.pop('sandwich')
print(my_dict['burger'])
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
ACTIVITY 10.13.1:
Enter the output of dictionary methods.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 62/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
368708.2344834.qx3zqy7
Start
airport_codes = {
'Washington': 'IAD',
'Tokyo': 'NRT',
©zyBooks 01/03/22 22:13 1172417
'Minneapolis': 'MSP',
Bharathi Byreddy
'Amsterdam': 'AMS',
LOUISVILLEMSBAPrep2DaviesWinter2022
'New York': 'JFK'
print(airport_codes.get('Amsterdam', 'na'))
print(airport_codes.get('Atlanta', 'na'))
1 2 3
Check Next
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
for key in dictionary: # Loop expression
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 63/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
The dict type also supports the useful methods items(), keys(), and values() methods, which produce
a view object. A view object provides read-only access to dictionary keys and values. A program can
iterate over a view object to access one key-value pair, one key, or one value at a time, depending on
the method used. A view object reflects any updates made to a dictionary, even if the dictionary is
altered after the view object is created.
The following examples show how to iterate over a dictionary using the above methods:
dict.items()
num_calories = dict(Coke=90,
Coke_zero=0, Pepsi=94)
print(f'{soda}: {calories}')
Coke: 90
Coke_zero: 0
Pepsi: 94
dict.keys() dict.values()
print(soda)
print(soda)
Coke
90
©zyBooks 01/03/22 22:13 1172417
Coke_zero
0
Bharathi Byreddy
Pepsi 94 LOUISVILLEMSBAPrep2DaviesWinter2022
When a program iterates over a view object, one result is generated for each iteration as needed,
instead of generating an entire list containing all of the keys or values. Such behavior allows the
interpreter to save memory. Since results are generated as needed, view objects do not support
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 64/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
indexing. A statement such as my_dict.keys()[0] produces an error. Instead, a valid approach is to use
the list() built-in function to convert a view object into a list, and then perform the necessary
operations. The example below converts a dictionary view into a list, so that the list can be sorted to
find the first two closest planets to Earth.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
solar_distances = dict(mars=219.7e6, venus=116.4e6,
jupiter=546e6, pluto=2.95e9)
list_of_distances = list(solar_distances.values()) #
Convert view to list
Closest planet is
sorted_distance_list = sorted(list_of_distances)
1.1640e+08
closest = sorted_distance_list[0]
Second closest planet
is 2.1970e+08
next_closest = sorted_distance_list[1]
The dict.items() method is particularly useful, as the view object that is returned produces tuples
containing the key-value pairs of the dictionary. The key-value pairs can then be unpacked at each
iteration, similar to the behavior of enumerate(), providing both the key and the value to the loop body
statements without requiring extra code.
Print the name and grade percentage of the student with the
highest total of points.
Find the average score of each assignment.
Find and apply a curve to each student's total score, such that the
©zyBooks 01/03/22 22:13 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
Load default template... Run
1
2 # student_grades contains sc
3 student_grades = {
4 'Andrew': [56, 79, 90, 2
5 'Nisreen': [88, 62, 68,
6 'Alan': [95 88 92 85
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 65/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
6 Alan : [95, 88, 92, 85,
7 'Chang': [76, 88, 85, 82
8 'Tricia': [99, 92, 95, 8
9 }
10
11
12
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY 10.14.1:
Iterating over dictionaries.
Fill in the code, using the dict methods items(), keys(), or values() where appropriate.
print(key)
if value < 0:
my_dict[key] = 0
for v in :
Bharathi Byreddy
print(2 * v)
LOUISVILLEMSBAPrep2DaviesWinter2022
CHALLENGE
10.14.1:
Report country population.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 66/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
ACTIVITY
'China:1365830000,India:1247220000,United States:318463000,Indonesia:252164800':
368708.2344834.qx3zqy7
1 user_input = input()
2 entries = user_input.split(',')
3 country_pop = {}
4
5 for pair in entries:
6 split_pair = pair.split(':')
7 country_pop[split_pair[0]] = split_pair[1]
8 # country_pop is a dictionary, Ex: { 'Germany':'82790000', 'France':'67190000'
9
10 ''' Your solution goes here '''
11
12 print(country, 'has', pop, 'people.')
Run
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
info This section has been set as optional by your instructor.
A dictionary may contain one or more nested dictionaries, in which the dictionary contains another
dictionary as a value. Consider the following code:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 67/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
students = {}
print('Jose:')
Jose:
Grade: 1172417
Bharathi Byreddy
ID: 22321
print(f' Grade: {students ["Jose"]["Grade"]}')
LOUISVILLEMSBAPrep2DaviesWinter2022
The variable students is first created as an empty dictionary. An indexing operation creates a new
entry in students with the key 'Jose' and the value of another dictionary. Indexing operations can be
applied to the nested dictionary by using consecutive sets of brackets []: The expression
students['Jose']['Grade'] first obtains the value of the key 'Jose' from students, yielding the
nested dictionary. The second set of brackets indexes into the nested dictionary, retrieving the value of
the key 'Grade'.
Nested dictionaries also serve as a simple but powerful data structure. A data structure is a method
of organizing data in a logical and coherent fashion. Actually, container objects like lists and dicts are
already a form of a data structure, but nesting such containers provides a programmer with much
more flexibility in the way that the data can be organized. Consider the simple example below that
implements a gradebook using nested dictionaries to organize students and grades.
Homework 0: 50
Homework 1: 52
Homework 2: 78
Midterm: 40
Final: 65
....
©zyBooks
Enter01/03/22
student 22:13
name: 1172417
John
Bharathi Byreddy
Ponting
Homework 0: 79
LOUISVILLEMSBAPrep2DaviesWinter2022
Homework 1: 80
Homework 2: 74
Midterm: 85
Final: 92
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 68/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
grades = {
'John Ponting': {
'Midterm': 85,
'Final': 92
},
'Jacques Kallis': {
'Midterm': 87,
'Final': 75
©zyBooks 01/03/22 22:13 1172417
},
Bharathi Byreddy
'Ricky Bobby': {
LOUISVILLEMSBAPrep2DaviesWinter2022
'Homeworks': [50, 52, 78],
'Midterm': 40,
'Final': 65
},
if user_input in grades:
homeworks = grades[user_input]['Homeworks']
midterm = grades[user_input]['Midterm']
final = grades[user_input]['Final']
# print info
print(f'Midterm: {midterm}')
print(f'Final: {final}')
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Note the whitespace and indentation used to layout the nested dictionaries. Such layout improves the
readability of the code and makes the hierarchy of the data structure obvious. The extra whitespace
does not affect the dict elements, as the interpreter ignores indentation in a multi-line construct.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 69/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
A benefit of using nested dictionaries is that the code tends to be more readable, especially if the keys
are a category like 'Homeworks'. Alternatives like nested lists tend to require more code, consisting of
more loops constructs and variables.
Dictionaries support arbitrary levels of nesting; Ex: The expression
students['Jose']['Homeworks'][2]['Grade'] might be applied to a dictionary that has four
levels of nesting.
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
10.15.1:
Nested dictionaries.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 70/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
True
False
Bharathi Byreddy
'x'}} is valid.
True
False
Conversion specifiers
Program output commonly includes the values of variables as a part of the text. A string formatting
expression allows a programmer to create a string with placeholders that are replaced by the values
of variables. Such a placeholder is called a conversion specifier, and different conversion specifiers
are used to perform a conversion of the given variable value to a different type when creating the
string.
Conversion specifiers convert the object into the desired type. Thus, if the programmer gives a float
value of 5.5 to a '%d' conversion specifier, a truncated integer value of '5' is the result.
The syntax for using a conversion specifier also includes a % symbol between the string and the value
or variable to be placed into the string. Ex: print('The couch is %d years old.' % couch_age)
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY 10.16.1:
Using string formatting expressions.
Animation captions:
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 71/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Conversion
Notes Example Output
specifier(s)
print('%d'
%d Substitute as integer. % 10)
10
print('%f'
%f Substitute as floating-point decimal % 15.2)
15.200000
print('%s'
%s Substitute as string. % 'ABC')
ABC
410.9
©zyBooks 01/03/22 22:13 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
1 apr = float(input('Enter APR:
2
Run
3 # Print using a float convers
4 print('Annual percentage rate
5
6 # Print using a decimal conve
7 print('Annual percentage rate
8
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 72/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
PARTICIPATION
ACTIVITY
10.16.2:
String formatting.
Complete the code using formatting specifiers to generate the described output.
I saved $150!
Multiple conversion specifiers can appear within the string formatting expression. Expressions that
contain more than one conversion specifier must specify the values within a tuple following the '%'
character. The following print statement will print a sentence including two numeric values, indicated
by the conversion specifiers %d and %f.
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Figure 10.16.1: Multiple conversion specifiers.
years = 15
Savings after 15 years is:
total = 500 * (years * 0.02)
150.000000
print('Savings after %d years is: %f' % (years,
total))
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 73/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
PARTICIPATION
ACTIVITY 10.16.3:
Multiple conversion specifiers.
Complete the code using formatting specifiers to generate the described output. Use the
indicated variables. ©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
The burrito is $5
print('The is $%d' %
(item, price))
print('The %s is
pounds.' % (item, weight))
Bharathi Byreddy
CHALLENGE LOUISVILLEMSBAPrep2DaviesWinter2022
ACTIVITY
10.16.1:
Printing a string.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 74/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Amy,5
368708.2344834.qx3zqy7
1 user_word = str(input())
2 user_number = int(input())
©zyBooks 01/03/22 22:13 1172417
3 Bharathi Byreddy
Run
CHALLENGE
ACTIVITY
10.16.2:
String formatting.
368708.2344834.qx3zqy7
a programmer to create a string with placeholders that are replaced by values or variable values at
LOUISVILLEMSBAPrep2DaviesWinter2022
execution. A placeholder surrounded by curly braces { } is called a replacement field. Values inside
the format() parentheses are inserted into the replacement fields in the string.
PARTICIPATION
ACTIVITY
10.17.1:
String formatting.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 75/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Animation content:
undefined
Animation captions:
1. The first replacement field {} in the string is replaced with the first value in the format()
©zyBooks 01/03/22 22:13 1172417
2. The next replacement field uses the next value, and so on.
LOUISVILLEMSBAPrep2DaviesWinter2022
Replacement Formatted
Example
definition string result
Named replacement allows a programmer to create a keyword argument that defines a name and
value in the format() parentheses. The name can then be placed into a replacement field. Ex:
animal='cat' is a keyword argument that can be used in a replacement field like {animal} to insert
the word "cat". Good practice is to use named replacement when formatting strings with many
replacement fields to make the code more readable. ©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
Note: The positional and inferred positional replacement types cannot be combined. Ex:
LOUISVILLEMSBAPrep2DaviesWinter2022
'{} + {1} is {2}'.format(2, 2, 4) is not allowed. However, named and either positional
replacement type can be combined. Ex: '{} + {} is {sum}'.format(2, 2, sum = 4)
Double braces {{ }} can be used to place an actual curly brace into a string. Ex:
'{0} {{Bezos}}'.format('Amazon') produces the string "Amazon {Bezos}".
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 76/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
PARTICIPATION 10.17.2:
Positional and named replacement in format strings.
ACTIVITY
Animation content:
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
1. Empty replacement fields infer their position based on the order of values in format().
2. Numbers in replacement fields indicate the position of the value in format().
3. Names in replacement fields indicate a named keyword from format(). Replacement fields can
appear more than once in the format.
PARTICIPATION
ACTIVITY
10.17.3:
string.format() usage.
1) print('April {},
{}'.format(22, 2020))
print(date.format(22, 2020))
print(date.format(22, 2020))
print(date.format(23, 2024))
Bharathi Byreddy
4) print('{0}:{1}'.format(9, 43))
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 77/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
5) print('{0}:{0}'.format(9, 43))
6) print('Hi
{{{0}}}!'.format('Bilbo'))
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
7) month = 'April'
day = 22
print('Today is {month}
{0}'.format(day, month=month))
Format specifications
A format specification inside of a replacement field allows a value's formatting in the string to be
customized. Ex: Using a format specification, a variable with the integer value 4 can be output as a
floating-point number (4.0) or with leading zeros (004).
A common format specification is to provide a presentation type for the value, such as integer (4),
floating point (4.0), fixed precision decimal (4.000), percentage (4%), binary (100), etc. A presentation
type can be set in a replacement field by inserting a colon : and providing one of the presentation type
characters described below.
'
©zyBooks 01/03/22 22:13 1172417
LOUISVILLEMSBAPrep2DaviesWinter2022
String (default presentation '{:s}'.format('Aiden')
s Aiden
type - can be omitted)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 78/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
f 4.000000
of precision) LOUISVILLEMSBAPrep2DaviesWinter2022
Fixed-point notation
.[precision]f (programmer-defined '{:.2f}'.format(4)
4.00
precision)
PARTICIPATION
ACTIVITY
10.17.4:
Format specifications and presentation types.
Enter the most appropriate format specification to produce the desired output.
print('{: }'.format(num))
print('{: }'.format(num))
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
3) The value of num as a binary (base
2) integer: 11111
num = 31
print('{: }'.format(num))
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 79/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
The colon : in the replacement field separates the "what" on the left from the "how" on the right. The
left "what" side references a value in the format() parentheses. The left side may be omitted (inferred
positional replacement), a number (positional replacement), or a name (named replacement). The
©zyBooks 01/03/22
right "how" side determines how to show the value, such as a presentation 22:13advanced
type. More 1172417
Bharathi Byreddy
Replacement
Example Output
type
PARTICIPATION
ACTIVITY 10.17.5:
Matching code blocks to formatted strings.
Match each code block to the code output. If the code would generate an error, mark as
"Error".
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 80/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
25 + 50 = 75
50 + 25 = 75
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Error
Reset
CHALLENGE
ACTIVITY
10.17.1:
String Formatting.
368708.2344834.qx3zqy7
CHALLENGE
ACTIVITY
10.17.2:
Printing a string.
Amy,5
368708.2344834.qx3zqy7
1 user_word = input()
2 user_number = int(input())
3
4 ''' Your solution goes here '''
5 ©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 81/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Run
CHALLENGE
ACTIVITY
10.17.3:
String formatting. ©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
368708.2344834.qx3zqy7
Mapping keys
Sometimes a string contains many conversion specifiers. Such strings can be hard to read and
understand. Furthermore, the programmer must be careful with the ordering of the tuple values, lest
items are mistakenly swapped. A dictionary may be used in place of a tuple on the right side of the
conversion operator to enhance clarity at the expense of brevity. If a dictionary is used, then all
conversion specifiers must include a mapping key component. A mapping key is specified by
indicating the key of the relevant value in the dictionary within parentheses.
PARTICIPATION
ACTIVITY 10.18.1:
Using a dictionary and conversion specifiers with mapping keys.
Animation captions:
1. A mapping key is specified by indicating the key of the relevant value in the dict within
parentheses.
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Figure 10.18.1: Comparing conversion operations using tuples and
dicts.
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 82/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
import time
...
LOUISVILLEMSBAPrep2DaviesWinter2022
Time is: 06/07/2013 20:16 28 sec
import time
...
PARTICIPATION
ACTIVITY
10.18.2:
Mapping keys.
Complete the print statement to produce the given output using mapping keys.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
2) "My name is Jerome and I'm 15
years old."
print ('My name is %(name)s and
I am %(age)d years old' % {
})
(1) Prompt the user to enter four numbers, each corresponding to a person's weight
Bharathi in pounds.
Byreddy
Store
all weights in a list. Output the list. (2 pts)
LOUISVILLEMSBAPrep2DaviesWinter2022
Ex:
Enter weight 1:
236.0
Enter weight 2:
89.5
Enter weight 3:
176.0
Enter weight 4:
166.3
(2) Output the average of the list's elements with two digits after the decimal point. Hint: Use a
conversion specifier to output with a certain number of digits after the decimal point. (1 pt)
(3) Output the max list element with two digits after the decimal point. (1 pt)
Ex:
Enter weight 1:
236.0
Enter weight 2:
89.5
Enter weight 3:
176.0
Enter weight 4:
166.3
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
(4) Prompt the user for a number between 1 and 4. Output the weight at the user specified location
(Hint: the actual list location will be this value minus one) and the corresponding value in kilograms. 1
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 84/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
Ex:
LOUISVILLEMSBAPrep2DaviesWinter2022
(5) Sort the list's elements from least heavy to heaviest weight. (2 pts)
Ex:
NaN.2344834.qx3zqy7
LAB
ACTIVITY 10.19.1:
LAB: Warm up: People's weights (Lists) 0/9
1 # FIXME (1): Prompt for four weights. Add all weights to a list. Output list.
2
3 # FIXME (2): Output average of weights.
4
5 # FIXME (3): Output max weight from list.
6
7 # FIXME (4): Prompt the user for a list index and output that weight in pounds and kil
8
9 # FIXME (5): Sort the list and output it.
Bharathi Byreddy
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 85/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
trending_flat trending_flat
main.py
Run program Input (from above)
(Your program)
Outp
Bharathi Byreddy
10 -7 4 39 -6 12 2
2 4 10 12 39
For coding simplicity, follow every output value by a space. Do not end with newline.
NaN.2344834.qx3zqy7
LAB
ACTIVITY
10.20.1:
LAB: Filter and sort a list 0 / 10
©zyBooks 01/03/22
Load22:13 1172417
main.py default
Bharathi Byreddy
template...
LOUISVILLEMSBAPrep2DaviesWinter2022
1 ''' Type your code here. '''
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 86/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
trending_flat trending_flat
main.py
Run program Input (from above)
(Your program)
Outp
History of your effort will appear here once you begin working
on this zyLab.
pairs that
Bharathi Byreddy
consist of a name and a phone number (both strings) and create a dictionary from them (the person's
LOUISVILLEMSBAPrep2DaviesWinter2022
name is the key and their phone number is the value) . These pairs are followed by a name, and your
program should look up and output the phone number associated with that name.
Ex: If the input is:
Frank
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 87/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
867-5309
NaN.2344834.qx3zqy7
LAB
ACTIVITY
10.21.1:
LAB: Contact list 0 / 10
©zyBooks 01/03/22 22:13 1172417
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
main.py Load default template...
trending_flat trending_flat
main.py
Run program Input (from above)
(Your program)
Outp
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 88/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home
History of your effort will appear here once you begin working
on this zyLab.
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 89/89