0% found this document useful (0 votes)
331 views

10 Chapter

Uploaded by

Bharathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
331 views

10 Chapter

Uploaded by

Bharathi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 89

1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

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

1. The user creates a new list. LOUISVILLEMSBAPrep2DaviesWinter2022


2. The interpreter creates a new object for each list element.
3. 'my_list' holds references to objects in list.

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

Accessing list elements

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

easily lookup the (i+1)th element in a list. Bharathi Byreddy

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...

1 oldest_people = [122, 119, 11


2 Run
3 nth_person = int(input('Enter
4
5 if (nth_person >= 1) and (nth
6 print(f'The {nth_person}t
7

©zyBooks 01/03/22 22:13 1172417

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.

PARTICIPATION ©zyBooks 01/03/22 22:13 1172417

ACTIVITY
10.1.2:
List indices. Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Given the following code, what is the output of each code segment?

animals = ['cat', 'dog', 'bird', 'raptor']

print(animals[0])

1) print(animals[0])

Check Show answer

2) print(animals[2])

Check Show answer

3) print(animals[0 + 1])

Check Show answer

4)

i = 3

print(animals[i])

Check Show answer


©zyBooks 01/03/22 22:13 1172417

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

Table 10.1.1: Some common list operations.

Example
Operation Description Example code
output

my_list ©zyBooks
= [1, 2,01/03/22
3]
22:13 1172417

my_list = [1, 2, 3] Creates a list. [1,


2, 3]
print(my_list)
Bharathi Byreddy
LOUISVILLEMSBAPrep2DaviesWinter2022

my_list = list('123')
['1',
list(iter) Creates a list. print(my_list)
'2', '3']

Get an element from my_list = [1, 2, 3]

my_list[index] print(my_list[1])
2
a list.

Get a new list


containing some of my_list = [1, 2, 3]

my_list[start:end] print(my_list[1:3])
[2, 3]
another list's
elements.

Get a new list with


elements of my_list2 my_list = [1, 2] + [3]

my_list1 + my_list2 print(my_list)


[1, 2, 3]
added to end of
my_list1.

Change the value of my_list = [1, 2, 3]

my_list[i] = x the ith element in- my_list[2] = 9


[1, 2, 9]
print(my_list)

place.

Add the elements in


[x] to the end of
my_list = [1, 2, 3]

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]

Delete an element del my_list[1]

del my_list[i] [1, 3]


from a list. print(my_list)

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.

©zyBooks 01/03/22 22:13 1172417

Animation captions: Bharathi Byreddy

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

<< First < Back Step 1 of 5 Forward > Last >>

line that has just executed


next line to execute

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

<< First < Back Step 1 of 5 Forward > Last >>

line that has just executed


next line to execute

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.

Animation content: ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
undefined

Animation captions:

1. Indexing operation changes list elements.


2. The list does not change when fav_color is updated.

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.

1) A program can modify the elements of


an existing list. ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

True LOUISVILLEMSBAPrep2DaviesWinter2022

False

2) The size of a list is determined when


the list is created and cannot change.
True
False

3) All elements of a list must have the


same type.
True
False

4) The statement del my_list[2]


produces a new list without the
element in position 2.
True
False

5) The statement my_list1 + my_list2


produces a new list.
True
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

Type the program's output

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.

Sample output with input: 'Gertrude Sam Ann Joseph'

['Sam', 'Ann', '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)

©zyBooks 01/03/22 22:13 1172417

Run Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

10.2 List methods


https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 8/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

Common list methods

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

object. Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Table 10.2.1: Available list methods.

Final
List method Description Code example my_list
value

Adding elements

Add an item to the end of my_list = [5, 8]


[5, 8,
list.append(x) 16]
list. my_list.append(16)

my_list = [5, 8]
[5, 8,
list.extend([x]) Add all items in [x] to list. 4, 12]
my_list.extend([4, 12])

Insert x into list before my_list = [5, 8]


[5,
list.insert(i, x) 1.7, 8]
position i. my_list.insert(1, 1.7)

Removing elements

Remove first item from list with my_list = [5, 8, 14]


[5,
list.remove(x) 14]
value x. my_list.remove(8)
©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

[5,
LOUISVILLEMSBAPrep2DaviesWinter2022
8]
my_list = [5, 8, 14]

list.pop() Remove and return last item in list. val


val = my_list.pop()
is
14

list.pop(i) Remove and return item at my_list = [5, 8, 14]


[8,
14]
position i in list. val = my_list.pop(0)
https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 9/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

val
is 5

Modifying elements

©zyBooks 01/03/22 22:13 1172417

Bharathi
my_list = [14, 5, 8] Byreddy

[5,
8,
list.sort() Sort the items of list in-place. LOUISVILLEMSBAPrep2DaviesWinter2022
14]
my_list.sort()

Reverse the elements of list in- my_list = [14, 5, 8]


[8, 5,
list.reverse() 14]
place. my_list.reverse()

Miscellaneous

Return index of first item in my_list = [5, 8, 14]


Prints
list.index(x)
list with value x. print(my_list.index(14)) "2"

Count the number of times my_list = [5, 8, 5, 5, 14]


Prints
list.count(x)
value x is in list. print(my_list.count(5)) "3"

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

1. vals is a list containing elements 1, 4, and 16.


2. The statement vals.append(9) appends element 9 to the end of the list.
3. The statement vals.insert(2, 18) inserts element 18 into position 2 of the list.
4. The statement vals.pop() removes the last element, 9, from the list.
5. The statement vals.remove(4) removes the first instance of element 4 from the list.
6. The statement vals.remove(55) removes the first instance of element 55 from the list. The list
does not contain the element 55 so vals is the same.
©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

zyDE 10.2.1: Amusement park ride reservation system.


The following (unfinished) program implements a digital line queuing
system for an amusement park ride. The system allows a rider to
reserve a place in line without actually having to wait. The rider simply
enters a name into a program to reserve a place. Riders that purchase
a VIP pass get to skip past the common riders up to the last VIP rider in
line. VIPs board the ride first. (Considering the average wait time for a
Disneyland ride is about 45 minutes, this might be a useful program.)
For this system, an employee manually selects when the ride is
dispatched (thus removing the next riders from the front of the line).
Complete the following program, as described above. Once finished,
add the following commands:

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.

Load default template...

 
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

10 '(5) Exit.\n\n') LOUISVILLEMSBAPrep2DaviesWinter2022


11
12 user_input = input(menu).strip().lower()
13
14 while user_input != '5':
15 if user_input == '1': # Add rider
16 name = input('Enter name:').strip().lower()
17 print(name)

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

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

PARTICIPATION
ACTIVITY 10.2.2:
List methods.

1) What is the output of the following


program?
temps = [65, 67, 72, 75]

temps.append(77)
print(temps[-1])

Check Show answer

2) What is the output of the following


program?
actors = ['Pitt', 'Damon']

actors.insert(1, 'Affleck')

print(actors[0], actors[1],
actors[2])

Check Show answer

3) Write the simplest two statements


that first sort my_list, then remove
the largest value element from the
list, using list methods. ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

4) Write a statement that counts the


number of elements of my_list that

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 12/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

have the value 15.

Check Show answer

CHALLENGE ©zyBooks 01/03/22 22:13 1172417

ACTIVITY
10.2.1:
Reverse sort of list. Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Sort short_names in reverse alphabetic order.

Sample output with input: 'Jan Sam Ann Joe Tod'

['Tod', 'Sam', 'Joe', 'Jan', 'Ann']

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

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

10.3 Iterating over a list

info This section has been set as optional by your instructor.

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

Figure 10.3.1: Iterating through a list. LOUISVILLEMSBAPrep2DaviesWinter2022

for my_var in my_list:

# Loop body statements go here

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:

Figure 10.3.2: Iterating through a list example: Finding the maximum


even number.

©zyBooks 01/03/22 22:13 1172417

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

user_input = input('Enter numbers:')

tokens = user_input.split() # Split into separate strings

# Convert strings to integers

nums = []

for token in tokens:

nums.append(int(token))

# Print each position and number


©zyBooks 01/03/22 22:13 1172417

print() # Print a single newline


Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
for index in range(len(nums)):

value = nums[index]

print(f'{index}: {value}')

# Determine maximum even number

max_num = None

for num in nums:

if (max_num == None) and (num % 2 == 0):

# First even number found

max_num = num

elif (max_num != None) and (num > max_num ) and (num % 2 == 0):

# Larger even number found

max_num = num

print('Max even #:', max_num)

Enter numbers:3 5 23 -1 456 1 6 83

0: 3

1: 5

2: 23

3: -1

4: 456

5: 1

6: 6

7: 83

Max even #: 456

....

Enter numbers:-5 -10 -44 -2 -27 -9 -27 -9

0:-5

1:-10

2:-44

3:-2

4:-27

5:-9

6:-27

7:-9

Max even #: -2

©zyBooks 01/03/22 22:13 1172417

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:

1. Loop iterates over all elements of list nums.


2. Only larger even numbers update the value of max_num.
3. Odd numbers, or numbers smaller than max_num, are ignored.
4. When the loop ends, max_num is set to the largest even number 456.

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.

Fill in the missing field to complete the program.

1) Count how many odd numbers


(cnt_odd) there are.
cnt_odd =

for i in num:
©zyBooks 01/03/22 22:13 1172417

if i % 2 == 1:
Bharathi Byreddy

cnt_odd += 1
LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

2) Count how many negative


numbers (cnt_neg) there are.

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:

Check Show answer

©zyBooks 01/03/22 22:13 1172417

3) Determine the number of elements Bharathi Byreddy

in the list that are divisible by 10. LOUISVILLEMSBAPrep2DaviesWinter2022


(Hint: the number x is divisible by
10 if x % 10 is 0.)
div_ten = 0

for i in num:

if :

div_ten += 1

Check Show answer

IndexError and enumerate()

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:

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: list assignment index out of range

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

Compute the average, as well as the sum. Hint: You don't


actually have to change the loop, but rather change the printed
value.
Print each number that is greater than 21.

203 12 5 800 -10


Load default template...
©zyBooks 01/03/22 22:13 1172417

 
1 # User inputs string w/ n Bharathi Byreddy

2 user_input = input('Enter LOUISVILLEMSBAPrep2DaviesWinter2022


Run
3
4 tokens = user_input.split
5
6 # Convert strings to inte
7 print()
8 nums = []
9 for pos, token in enumera
10 nums.append(int(token
11 print(f'{pos}: {token
12
13 sum = 0
14 for num in nums:
15 sum += num
16
17 print('Sum:', sum)

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.

Built-in functions that iterate over lists

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.

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

Table 10.3.1: Built-in functions supporting list objects.


LOUISVILLEMSBAPrep2DaviesWinter2022

Example
Function Description Example code
output

all(list) True if every element in list is True print(all([1, 2, 3]))


True

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

True if any element in the list is print(any([0, 2]))


True

any(list) False
True. print(any([0, 0]))

Get the maximum element in the


max(list) print(max([-3, 5, 25])) 25
list.

Get the minimum element in the


min(list) print(min([-3,
©zyBooks5, 25]))22:13-3
01/03/22 1172417

list. Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
Get the sum of all elements in the
sum(list) print(sum([-3, 5, 25])) 27
list.

zyDE 10.3.2: Using built-in functions with lists.


Complete the following program using functions from the table above
to find some statistics about basketball player Lebron James. The code
below provides lists of various statistical categories for the years 2003-
2013. Compute and print the following statistics:

Total career points


Average points per game
Years of the highest and lowest scoring season

Use loops where appropriate.

Load default template... Run

 
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

10 # Print Average PPG


Bharathi Byreddy

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.

Assume that my_list is [0, 5, 10, 15].

1) What value is returned by


sum(my_list)?
©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
Check Show answer

2) What value is returned by


max(my_list)?

Check Show answer

3) What value is returned by


any(my_list)?

Check Show answer

4) What value is returned by


all(my_list)?

Check Show answer

5) What value is returned by


min(my_list)?

Check Show answer


©zyBooks 01/03/22 22:13 1172417

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

Sample output with input:

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)

©zyBooks 01/03/22 22:13 1172417

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'

90 -> 92 -> 94 -> 95

Note: 95 is followed by a space, then a newline.


368708.2344834.qx3zqy7

1 user_input = input()
2 hourly_temperature = user_input.split()
3
4 ''' Your solution goes here '''
5

©zyBooks 01/03/22 22:13 1172417

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.

©zyBooks 01/03/22 22:13 1172417

10.4 List games Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

info This section has been set as optional by your instructor.

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

Next value Store value

Time - Best time -


Clear best

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

Next value Increment

Time - Best time -


Clear best ©zyBooks 01/03/22 22:13 1172417

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

Next value Swap values

Time - Best time -


Clear best

10.5 List nesting


Since a list can contain any type of object as an element, and a list is itself an object, a list can contain
another list as an element. Such embedding of a list inside another list is known as list nesting.Ex:
The code my_list = [[5, 13], [50, 75, 100]] creates a list with two elements that are each
©zyBooks 01/03/22 22:13 1172417

another list. Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Figure 10.5.1: Multi-dimensional lists.

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 24/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

my_list = [[10, 20], [30, 40]]


First nested list: [10, 20]

print('First nested list:', my_list[0])


Second nested list: [30, 40]

print('Second nested list:', my_list[1])


Element 0 of first nested
list: 10
print('Element 0 of first nested list:',
my_list[0][0])

©zyBooks 01/03/22 22:13 1172417

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:

1. The nested lists can be accessed using a single access operation.


2. The elements of each nested list can be accessed using two indexing operations.

PARTICIPATION
ACTIVITY 10.5.2:
List nesting.

1) Given the list nums = [[10, 20, 30],


[98, 99]], what does nums[0][0]
evaluate to?

Check Show answer

2) Given the list nums = [[10, 20, 30],


[98, 99]], what does nums[1][1]
evaluate to?

Check Show answer

3) Given the list nums = [[10, 20, 30], ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

[98, 99]], what does nums[0] LOUISVILLEMSBAPrep2DaviesWinter2022


evaluate to?

Check Show answer

4) Create a nested list called nums


https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 25/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

whose only element is the list [21,


22, 23].

Check Show answer

©zyBooks 01/03/22 22:13 1172417

A list is a single-dimensional sequence of items, like a series of times, data samples,


Bharathi daily
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:

Figure 10.5.2: Representing a tic-tac-toe board using nested lists.

tic_tac_toe = [

['X', 'O', 'X'],

[' ', 'X', ' '],

['O', 'O', 'X']

X O X

]
X


O O X
print(tic_tac_toe[0][0], tic_tac_toe[0][1], tic_tac_toe[0][2])

print(tic_tac_toe[1][0], tic_tac_toe[1][1], tic_tac_toe[1][2])

print(tic_tac_toe[2][0], tic_tac_toe[2][1], tic_tac_toe[2][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

1. New list object contains other lists as elements. Bharathi Byreddy

2. Elements accessed by [row][column]. LOUISVILLEMSBAPrep2DaviesWinter2022

zyDE 10.5.1: Two-dimensional list example: Driving distance between


cities.

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 26/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

The following example illustrates the use of a two-dimensional list in a


distance between cities example.

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

indentation to clearly indicate the elements of each list -- the spacing


LOUISVILLEMSBAPrep2DaviesWinter2022
does not affect how the interpreter evaluates the list contents.

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:

Figure 10.5.3: The level of nested lists is


arbitrary.

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.

©zyBooks 01/03/22 22:13 1172417

scores = [
Bharathi Byreddy

[75, LOUISVILLEMSBAPrep2DaviesWinter2022
100, 82, 76],

Assume the following list has been created


[85, 98, 89, 99],

[75, 82, 85, 5]

1) Write an indexing expression that


gets the element from scores
whose value is 100.

Check Show answer

2) How many elements does scores


contain? (The result of len(scores))

Check Show answer

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.

©zyBooks 01/03/22 22:13 1172417

Animation content: Bharathi Byreddy

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

Figure 10.5.4: Iterating through LOUISVILLEMSBAPrep2DaviesWinter2022


multi-dimensional lists using enumerate().

currency[0][0] is
1.00

currency[0][1] is
5.00

currency = [

currency[0][2] is
[1, 5, 10 ], # US Dollars
10.00

[0.75, 3.77, 7.53], #Euros


currency[1][0] is
[0.65, 3.25, 6.50] # British pounds
0.75

]
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

Actual output: [0, 2, 4, 6] [0, 3, 6, 9, 12]

[0, 2, 4, 6] [0, 3, 6, 9, 12]


©zyBooks 01/03/22 22:13 1172417

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(n2, end=' ')

print()

2) Desired output: X wins!

Actual output: Cat's game!

©zyBooks 01/03/22 22:13 1172417

tictactoe = [
Bharathi Byreddy

['X', 'O', 'O'],


LOUISVILLEMSBAPrep2DaviesWinter2022
['O', 'O', 'X'],

['X', 'X', 'X']

# Check for 3 Xs in one row

# (Doesn't check columns or diagonals)

for row in tictactoe

num_X_in_row = 0

for square in row

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.

Sample output with input: '1 2 3,2 4 6,3 6 9':

1 | 2 | 3

©zyBooks 01/03/22 22:13 1172417

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

10.6 List slicing


A programmer can use slice notation to read multiple elements from a list, creating a new list that
contains only the desired elements. The programmer indicates the start and end positions of a range
of elements to retrieve, as in my_list[0:2]. The 0 is the position of the first element to read, and the
2 indicates last element. Every element between 0 and 2 from my_list will be in the new list. The end
position, 2 in this case, is not included in the resulting list.

Figure 10.6.1: List slice notation.

boston_bruins = ['Tyler', 'Zdeno', 'Patrice']

print('Elements 0 and 1:', boston_bruins[0:2])


Elements 0 and 1: ['Tyler', 'Zdeno']
print('Elements 1 and 2:', boston_bruins[1:3])
Elements 1 and 2: ['Zdeno', 'Patrice']

©zyBooks 01/03/22 22:13 1172417

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:

1. The list object is created.


2. The list is sliced from 0 to 3, and then printed out.
3. The list is sliced from 1 up to 2.

Negative indices can also be used to count backwards from the ©zyBooks
end of the01/03/22
list. 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Figure 10.6.2: List slicing: Using negative indices.

election_years = [1992, 1996, 2000, 2004, 2008]

print(election_years[0:-1]) # Every year except the last

[1992, 1996, 2000,


print(election_years[0:-3]) # Every year except the last 2004]

three
[1992, 1996]

print(election_years[-3:-1]) # The third and second to [2000, 2004]


last years

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.

Assume that the following code has been evaluated:

nums = [1, 1, 2, 3, 5, 8, 13]

1) What is the result of nums[1:5]?

Check Show answer

©zyBooks 01/03/22 22:13 1172417

2) What is the result of nums[5:10]? Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

3) What is the result of nums[3:-1]?

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 32/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

Check Show answer

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.

Given the following code:

nums = [0, 25, 50, 75, 100]

1) The result of evaluating nums[0:5:2] is


[25, 75].
True
False

2) The result of evaluating nums[0:-1:3] is


[0, 75].
True
False

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).

Table 10.6.1: Some common list slicing operations.


©zyBooks 01/03/22 22:13 1172417

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

my_list[start:end:stride] Get a list of my_list = [5, 10, 20, 40, 80]


[5,
40]
every stride print(my_list[0:5:3])
element from
start to end
(minus 1).

Get a list
©zyBooks 01/03/22 22:13[20,
from start to my_list = [5, 10, 20, 40, 80]
1172417

my_list[start:] Bharathi Byreddy40,


end of the print(my_list[2:])


LOUISVILLEMSBAPrep2DaviesWinter2022
80]
list.

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:

my_list = [1, 1, 2, 3, 5, 8, 13, 21, 34]

my_list[3:6] my_list[3:1] ©zyBooks 01/03/22


my_list[len(my_list)//2:(len(my_list)//2) + 1]22:13 my_list[:20]
1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
my_list[2:5] my_list[4:]

[5, 8, 13, 21, 34]

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

[3, 5, 8] Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Reset

CHALLENGE
ACTIVITY 10.6.1:
List slicing.

368708.2344834.qx3zqy7

Start

Type the program's output

my_list = [13, 14, 15, 16, 17, 18, 19]

new_list = my_list[0:4]

print(new_list)

1 2 3 4

Check Next

10.7 Loops modifying lists

©zyBooks 01/03/22 22:13 1172417

info This section has been set as optional by your instructor.


Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Sometimes a program iterates over a list while modifying the elements, such as by changing some
elements' values, or by moving elements' positions.

Changing elements' values

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.

Figure 10.7.1: Modifying a list during iteration


example.
©zyBooks 01/03/22 22:13 1172417

my_list = [3.2, 5.0, 16.5, 12.25]


Bharathi Byreddy


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.

Figure 10.7.2: Modifying a list during iteration example: Converting


negative values to 0.

Correct way to modify the list.


Incorrect way: list not modified.

user_input = input('Enter numbers:')

tokens = user_input.split()

# Convert strings to integers

nums = []

for token in tokens:

nums.append(int(token))

# Print each position and number

print()

for pos, val in enumerate(nums):

print(f'{pos}: {val}')

# Change negative values to 0

for num in nums:

if num < 0:
©zyBooks 01/03/22 22:13 1172417

Bharathi
num = 0 # Logic error: Byreddy

temp
LOUISVILLEMSBAPrep2DaviesWinter2022
variable num set to 0

# Print new numbers

print('New numbers: ')

for num in nums:

print(num, end=' ')

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 36/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

user_input = input('Enter Enter numbers:5 67 -5 -4 5 6 6 4

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:

for token in tokens:


5 67 -5 -4 5 6 6 4 ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

nums.append(int(token))
LOUISVILLEMSBAPrep2DaviesWinter2022

# Print each position and


number

print()

for pos, val in


enumerate(nums):

print(f'{pos}: {val}')

# Change negative values


to 0

for pos in
range(len(nums)):

if nums[pos] < 0:

nums[pos] = 0

# Print new numbers

print('New numbers: ')

for num in nums:

print(num, end=' ')

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

©zyBooks 01/03/22 22:13 1172417

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 >

line that has just executed


next line to execute

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

<< First < Back Step 1 of 14 Forward > Last >

line that has just executed


next line to execute

Frames Objects

CHALLENGE
ACTIVITY
10.7.1:
Iterating through a list using range().

368708.2344834.qx3zqy7 ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

Start LOUISVILLEMSBAPrep2DaviesWinter2022

Type the program's output

user_values = [3, 6, 7]

for pos in range(len(user_values)):

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

Consider the following program:

nums = [10, 20, 30, 40, 50]

for pos in range(len(nums)):

tmp = nums[pos] / 2

if (tmp % 2) == 0:
nums[pos] = tmp

1) What's the final value of nums[1]?

Check Show answer

Changing list size

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.

Figure 10.7.3: Modifying lists while iterating: Incorrect program.

©zyBooks 01/03/22 22:13 1172417

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

user_input = input('Enter first set of numbers: 2: 15

')
3: 20

tokens = user_input.split() # Split into Enter second set of numbers:15


separate strings 20 25 30


0: 15

# Convert strings to integers


1: 20

print()
©zyBooks 01/03/22 22:13 1172417

2: 25

3: 30
Bharathi Byreddy

for pos, val in enumerate(tokens):


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()

# Convert strings to integers

print()

for pos, val in enumerate(tokens):

nums2.append(int(val))

print(f'{pos}: {val}')

# Remove elements from nums1 if also in nums2

print()

for val in nums1:

if val in nums2:

print(f'Deleting {val}')

nums1.remove(val)

# Print new numbers

print('\nNumbers only in first set:', end=' ')

for num in nums1:

print(num, end=' ')

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

Figure 10.7.4: Copy a list using [:].

for item in my_list[:]:

# Loop statements.

©zyBooks 01/03/22 22:13 1172417

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.

zyDE 10.7.1: Modify the above program to work correctly.


Modify the program (copied from above) using slice notation to iterate
over a copy of the list.

Pre-enter any input for program,


Load default template...
then press run.
 
1
2 nums1 = []
Run
3 nums2 = []
4
5 user_input = input('Enter
6 tokens = user_input.split(
7
8 # Convert strings to integ
9 for pos, val in enumerate(
10 nums1.append(int(val))
11
12 print(f'{pos}: {val}')
13 ©zyBooks 01/03/22 22:13 1172417

14 user_input = input('Enter Bharathi Byreddy

15 tokens = user_input.split( LOUISVILLEMSBAPrep2DaviesWinter2022


16
17 # Convert strings to integ

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

1) Iterating over a list and deleting


elements from the original list might
cause a logic program error.
True
False

2) A programmer can iterate over a copy ©zyBooks 01/03/22 22:13 1172417

of a list to safely make changes to that Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
list.
True
False

10.8 List comprehensions

info This section has been set as optional by your instructor.

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:

Construct 10.8.1: List comprehension.

new_list = [expression for loop_variable_name in iterable]

A list comprehension has three components: ©zyBooks 01/03/22 22:13 1172417

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.

Figure 10.8.1: List comprehension example: A first look.


©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

my_list = [10, 20, 30]


LOUISVILLEMSBAPrep2DaviesWinter2022
list_plus_5 = [(i + 5) for i in my_list]


New list contains: [15, 25, 35]
print('New list contains:', list_plus_5)

The following animation illustrates:

PARTICIPATION
ACTIVITY 10.8.1:
List comprehension.

Animation captions:

1. My list is created and holds integer values.


2. Loop variable i set to each element of my_list.

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.

Table 10.8.1: List comprehensions can replace some for loops.

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

Add 10 to 20, 50]

for i in Bharathi Byreddy

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)

2 Convert ['5', '20', '50']


every

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 43/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

element to my_list = [5, 20, 50]


my_list = [5,
a string. for i in 20, 50]

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)

inp = input('Enter inp =


©zyBooks 01/03/22 22:13 1172417

Convert numbers:')
input('Enter
Bharathi Byreddy

my_list = []
numbers:')

user input for i in inp.split():


my_list = Enter numbers: 7 9 3
LOUISVILLEMSBAPrep2DaviesWinter2022
3
into a list of [int(i) for i [7, 9, 3]
integers. my_list.append(int(i))
in inp.split()]

print(my_list)
print(my_list)

Find the my_list = [[5, 10, 15], my_list = [[5,


sum of [2, 3, 16], [100]]
10, 15], [2, 3,
sum_list = []
16], [100]]

each row in for row in my_list:


sum_list =
4 [30, 21, 100]
a two- [sum(row) for
dimensional sum_list.append(sum(row))
row in 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]]

smallest for row in my_list:


min_row =
5 min([sum(row) 21
sum in a
sum_list.append(sum(row))
for row in
two- min_row = min(sum_list)
my_list])

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

over the list returned by split(). Bharathi Byreddy

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

For the following questions, refer to the table above.

1) What's the output of the list


comprehension program in row 1 if
my_list is [-5, -4, -3]?

©zyBooks 01/03/22 22:13 1172417

Check Show answer


Bharathi Byreddy

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)

Check Show answer

3) What's the output of the list


comprehension program from row
3 if the user enters "4 6 100"?

Check Show answer

4) What's the output of the list


comprehension program in row 4 if
my_list is [[5, 10], [1]]?

Check Show answer

5) Alter the list comprehension from ©zyBooks 01/03/22 22:13 1172417

row 5 to calculate the sum of every Bharathi Byreddy

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

Check Show answer

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

as the loop variable. Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

1) Twice the value of each element in


the list variable x.

Check Show answer

2) The absolute value of each


element in x. Use the abs()
function to find the absolute value
of a number.

Check Show answer

3) The largest square root of any


element in x. Use math.sqrt() to
calculate the square root.

Check Show answer

Conditional list comprehensions

A list comprehension can be extended with an optional conditional clause that causes the statement
©zyBooks 01/03/22 22:13 1172417

to return a list with only certain elements.


Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Construct 10.8.2: Conditional list


comprehensions.

new_list = [expression for name in iterable if condition]

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.

Figure 10.8.2: Conditional list comprehension example: Return


©zyBooks 01/03/22a22:13
list of
1172417

Bharathi Byreddy

even numbers. LOUISVILLEMSBAPrep2DaviesWinter2022

# Get a list of integers from the user

numbers = [int(i) for i in input('Enter Enter numbers: 5 52 16 7 25

numbers:').split()]
Even numbers only: [52, 16]


....

Enter numbers: 8 12 -14 9 0

# Return a list of only even numbers

Even numbers only: [8, 12,


even_numbers = [i for i in numbers if (i % 2) == 0]
-14, 0]
print('Even numbers only:', even_numbers)

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.

1) Only negative values from the list x


numbers =

Check Show answer

2) Only negative odd values from the list x


numbers =

Check Show answer


©zyBooks 01/03/22 22:13 1172417

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

Type the program's output

my_list = [-1, 0, 1, 2]

new_list = [ number - 3 for number in my_list ]

print(new_list)

1 2 3

©zyBooks 01/03/22 22:13 1172417

Check Next Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

10.9 Sorting lists

info This section has been set as optional by your instructor.

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:

1. The list my_list is created and holds integer values.


2. The list is sorted in-place.

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.

Figure 10.9.1: list.sort() method example: Alphabetically sorting book


titles.

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 48/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

books = []

prompt = 'Enter new book: '

user_input = input(prompt).strip()
Enter new book: Pride, Prejudice, and Zombies


Enter new book: Programming in Python

Enter new book: Hackers and Painters


while (user_input.lower() != 'exit'):

Enter new book: World War Z

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.

numbers = [int(i) for i in input('Enter numbers:


').split()]

Enter numbers: -5 5 -100 23 4 5


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)

©zyBooks 01/03/22 22:13 1172417

PARTICIPATION Bharathi Byreddy

ACTIVITY
10.9.2:
list.sort() and sorted(). LOUISVILLEMSBAPrep2DaviesWinter2022

1) The sort() method modifies a list in-


place.
True
False

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 49/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

2) The output of the following is [13, 7, 5]:

primes = [5, 13, 7]

primes.sort()

print(primes)

True
False
©zyBooks 01/03/22 22:13 1172417

3) The output of print(sorted([-5, 5, Bharathi Byreddy

2])) is [2, -5, 5]. LOUISVILLEMSBAPrep2DaviesWinter2022

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.

Figure 10.9.3: Using the key argument.

names = []

prompt = 'Enter name: '

user_input = input(prompt)

while user_input != 'exit':

names.append(user_input)

user_input = input(prompt)

no_key_sort = sorted(names)

key_sort = sorted(names, key=str.lower)


©zyBooks 01/03/22 22:13 1172417

print('Sorting without key:', no_key_sort)


Bharathi Byreddy

print('Sorting with key: ', key_sort)


LOUISVILLEMSBAPrep2DaviesWinter2022

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 50/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

Enter name: Serena Williams

Enter name: Venus Williams

Enter name: rafael Nadal

Enter name: john McEnroe

Enter name: exit

Sorting without key: ['Serena Williams', 'Venus Williams', 'john McEnroe', 'rafael Nadal']

Sorting with key: ['john McEnroe', 'rafael Nadal', 'Serena Williams', 'Venus Williams']

©zyBooks 01/03/22 22:13 1172417

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).

Figure 10.9.4: The key argument to list.sort() or sorted() can be assigned


any function.

my_list = [[25], [15, 25, 35], [10, 15]]

sorted_list = sorted(my_list, key=max)


Sorted list: [[10, 15], [25], [15, 25, 35]]

print('Sorted list:', sorted_list)

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.

Provide an expression using x.sort that sorts the list x accordingly.

1) Sort the elements of x such that


the greatest element is in position
0. ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

2) Arrange the elements of x from


lowest to highest, comparing the

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 51/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

upper-case variant of each element


in the list.

Check Show answer

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

10.10 Command-line arguments

info This section has been set as optional by your instructor.

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:

> python myprog.py myfile1.txt

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.

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

Animation captions: LOUISVILLEMSBAPrep2DaviesWinter2022

1. Whitespace separates arguments.


2. User text is stored in sys.argv list.

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

Figure 10.10.1: Simple use of command line arguments.

> python myprog.py Tricia 12

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

print(f'{age} is a great age.\n')


Traceback (most recent call last):

File "myprog.py", line 4, in <module>

age = sys.argv[2]

IndexError: list index out of range

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.

Figure 10.10.2: Checking for proper number of command-line arguments.

import sys

> python myprog.exe Tricia


12

©zyBooks 01/03/22 22:13 1172417

if len(sys.argv) != 3:
Hello Tricia.Byreddy
12 is a

print('Usage: python myprog.py name age\n')


Bharathi
great age.

sys.exit(1) # Exit the program, indicating an LOUISVILLEMSBAPrep2DaviesWinter2022


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

print(f'Hello {name}. ')


Usage: python myprog.py
print(f'{age} is a great age.\n')
name age

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'].

> python myprog.py "Mary Jane" 65

PARTICIPATION
ACTIVITY 10.10.2:
Command-line arguments.

1) What is the value of sys.argv[1]


given the following command-line
input (include quotes in your
answer):
python prog.py
Tricia Miller 26

Check Show answer

2) What is the value of sys.argv[1]


given the following command-line
input (include quotes in your
answer):
python prog.py
'Tricia Miller' 26

Check Show answer


©zyBooks 01/03/22 22:13 1172417

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.

argparse: Parser for command-line options, arguments, and sub-commands


getopt: C-style parser for command-line options

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

10.11 Additional practice: Engineering examples

info This section has been set as optional by your instructor.

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.

zyDE 10.11.1: Calculate voltage drops across series of resistors.


The following program uses a list to store a user-entered set of
resistance values and computes I.

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:

5 resistors are in series.

This program calculates the voltage drop across each resistor.

Input voltage applied to circuit: 12.0

Input ohms of 5 resistors

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

Voltage drop per resistor is

1) 3.0 V

2) 1.4 V

3) 1.8 V

4) 3.7 V

5) 2.0 V

Load default template...

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

11 print (input_voltage) LOUISVILLEMSBAPrep2DaviesWinter2022


12
13
14 print(f'Input ohms of {num_resistors} resistors')
15 for i in range(num_resistors):
16
17 res = float(input(f'{i + 1}) '))

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.

zyDE 10.11.2: Matrix multiplication of 4x2 and 2x3 matrices.


The following illustrates matrix multiplication for 4x2 and 2x3 matrices
captured as two-dimensional lists.

Run the program below. Try changing the size and value of the
matrices and computing new values.

Load default template...


©zyBooks 01/03/22 22:13 1172417

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

Run ©zyBooks 01/03/22 22:13 1172417

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:

1. An English dictionary associates words with definitions.


2. A Python dictionary associates keys with values.

There are several approaches to create a dict:

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

The second approach uses dictionary comprehension,LOUISVILLEMSBAPrep2DaviesWinter2022


which evaluates a loop to create a new
dictionary, similar to how list comprehension creates a new list. Dictionary comprehension is out
of scope for this material.
Other approaches use the dict() built-in function, using either keyword arguments to specify the
key-value pairs or by specifying a list of tuple-pairs. The following creates equivalent
dictionaries:
dict(Bobby='805-555-2232', Johnny='951-555-0055')

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 57/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

dict([('Bobby', '805-555-2232'), ('Johnny', '951-555-0055')])

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.

Table 10.12.1: Common dict operations. ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Operation Description Example code

Indexing operation – retrieves the


my_dict[key] jose_grade = my_dict['Jose']
value associated with key.

Adds an entry if the entry does not


my_dict[key]
exist, else modifies the existing my_dict['Jose'] = 'B+'
= value
entry.

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'.

zyDE 10.12.1: Dictionary example: Gradebook.


Complete the program that implements a gradebook. The
student_grades dict should consist of entries whose keys are student
names, and whose values are lists of student scores.

Pre-enter any©zyBooks
input for 01/03/22
program,22:13 1172417

Load default template...


then press run. Bharathi Byreddy

  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.

1) Dictionary entries can be modified in-


place – a new dictionary does not need
to be created every time an element is
added, changed, or removed.
True
False

2) The variable my_dict created with the


following code contains two keys, 'Bob'
and 'A+'.

my_dict = dict(name='Bob',
grade='A+')

True
False

CHALLENGE
ACTIVITY 10.12.1:
Delete from dictionary.

Delete Prussia from country_capital.

Sample output with input: 'Spain:Madrid,Togo:Lome,Prussia: Konigsberg'

Prussia deleted? Yes.

©zyBooks 01/03/22 22:13 1172417

Spain deleted? No.


Bharathi Byreddy

Togo deleted? No.


LOUISVILLEMSBAPrep2DaviesWinter2022

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

13 if 'Prussia' in country_capital: Bharathi Byreddy

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

Type the program's output

airport_codes = {}

airport_codes['San Francisco'] = 'SFO'

airport_codes['Cincinnati'] = 'CVG'

airport_codes['Los Angeles'] = 'LAX'

print(airport_codes['San Francisco'])

print(airport_codes['Cincinnati'])

1 2 3

Check Next

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

10.13 Dictionary methods


A dictionary method is a function provided by the dictionary type (dict) that operates on a specific
dictionary object. Dictionary methods can perform some useful operations, such as adding or
removing elements, obtaining all the keys or values in the dictionary, merging dictionaries, etc.

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 60/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

Below are a list of common dictionary methods:

Table 10.13.1: Dictionary methods.

Dictionary method Description Code example Output


©zyBooks 01/03/22 22:13 1172417

Removes Bharathi Byreddy

my_dict = {'Ahmad': 1, 'Jane': 42}

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

my_dict.get(key, default) print(my_dict.get('Jane', 'N/A'))


N/A
does not
print(my_dict.get('Chad', 'N/A'))
exist in the
dictionary,
then
returns
default.

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

overwritten Bharathi Byreddy

if the same LOUISVILLEMSBAPrep2DaviesWinter2022


keys exist
in
my_dict2.

my_dict.pop(key, default) Removes my_dict = {'Ahmad': 1, 'Jane': 42}


{'Jane':
42}
and val = my_dict.pop('Ahmad')

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 61/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

returns the print(my_dict)


key value
from the
dictionary.
If key does
not exist,
then
©zyBooks 01/03/22 22:13 1172417

default is Bharathi Byreddy

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)

Check Show answer

2) my_dict['burger'] =
my_dict['sandwich']

val = my_dict.pop('sandwich')

print(my_dict['burger'])

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

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

Type the program's output

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'))

print(airport_codes.get('San Jose', 'na'))

1 2 3

Check Next

10.14 Iterating over a dictionary


As usual with containers, a common programming task is to iterate over a dictionary and access or
modify the elements of the dictionary. A for loop can be used to iterate over a dictionary object, the
loop variable being set to a key of an entry in each iteration. The ordering in which the keys are iterated
over is not necessarily the order in which the elements were inserted into the dictionary. The Python
interpreter creates a hash of each key. A hash is a transformation of the key into a unique value that
allows the interpreter to perform very fast lookup. Thus, the ordering is actually determined by the
hash value, but such hash values can change depending on the Python version and other factors.

Construct 10.14.1: A for loop over a dictionary


retrieves each key in the dictionary.
©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
for key in dictionary: # Loop expression

# Statements to execute in the loop

#Statements to execute after the loop

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.

dict.items() – returns a view object that yields (key, value) tuples.


©zyBooks 01/03/22 22:13 1172417

dict.keys() – returns a view object that yields dictionary keys.


Bharathi Byreddy

dict.values() – returns a view object that yields dictionary values.


LOUISVILLEMSBAPrep2DaviesWinter2022

The following examples show how to iterate over a dictionary using the above methods:

Figure 10.14.1: Iterating over a dictionary.

dict.items()

num_calories = dict(Coke=90,
Coke_zero=0, Pepsi=94)

for soda, calories in


num_calories.items():

print(f'{soda}: {calories}')

Coke: 90

Coke_zero: 0

Pepsi: 94

dict.keys() dict.values()

num_calories = dict(Coke=90, num_calories = dict(Coke=90,


Coke_zero=0, Pepsi=94)
Coke_zero=0, Pepsi=94)

for soda in num_calories.keys():


for soda in num_calories.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.

Figure 10.14.2: Use list() to convert view objects into lists.


©zyBooks 01/03/22 22:13 1172417

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]

print(f'Closest planet is {closest:.4e}')

print(f'Second closest planet is {next_closest:.4e}')

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.

zyDE 10.14.1: Iterating over a dictionary example: Gradebook statistics.


Write a program that uses the keys(), values(), and/or items() dict
methods to find statistics about the student_grades dictionary. Find the
following:

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

best student has 100% of the total points. Bharathi Byreddy

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

©zyBooks 01/03/22 22:13 1172417

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.

1) Print each key in the dictionary


my_dict.
for key in
:

print(key)

Check Show answer

2) Change all negative values in


my_dict to 0.
for key, value in
:

if value < 0:

my_dict[key] = 0

Check Show answer

3) Print twice the value of every value


in my_dict.
©zyBooks 01/03/22 22:13 1172417

for v in :
Bharathi Byreddy

print(2 * v)
LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

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

Write a loop that prints each country's population in country_pop.

Sample output with input:

'China:1365830000,India:1247220000,United States:318463000,Indonesia:252164800':

United States has 318463000 people.

©zyBooks 01/03/22 22:13 1172417

India has 1247220000 people.


Bharathi Byreddy

Indonesia has 252164800 people.


LOUISVILLEMSBAPrep2DaviesWinter2022
China has 1365830000 people.

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

10.15 Dictionary nesting


©zyBooks 01/03/22 22:13 1172417

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

Figure 10.15.1: Nested dictionaries.

students = {}

students ['Jose'] = {'Grade': 'A+', 'StudentID': 22321}

print('Jose:')
Jose:

©zyBooks 01/03/22 22:13A+

Grade: 1172417


Bharathi Byreddy

ID: 22321
print(f' Grade: {students ["Jose"]["Grade"]}')

LOUISVILLEMSBAPrep2DaviesWinter2022

print(f' ID: {students["Jose"]["StudentID"]}')

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.

Figure 10.15.2: Nested dictionaries example: Storing grades.

Enter student name: Ricky


Bobby

Homework 0: 50

Homework 1: 52

Homework 2: 78

Midterm: 40

Final: 65

Final percentage: 57.0%

....

©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

Final percentage: 82.0%

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': {

'Homeworks': [79, 80, 74],

'Midterm': 85,

'Final': 92

},

'Jacques Kallis': {

'Homeworks': [90, 92, 65],

'Midterm': 87,

'Final': 75
©zyBooks 01/03/22 22:13 1172417

},
Bharathi Byreddy

'Ricky Bobby': {
LOUISVILLEMSBAPrep2DaviesWinter2022
'Homeworks': [50, 52, 78],

'Midterm': 40,

'Final': 65

},

user_input = input('Enter student name: ')

while user_input != 'exit':

if user_input in grades:

# Get values from nested dict

homeworks = grades[user_input]['Homeworks']

midterm = grades[user_input]['Midterm']

final = grades[user_input]['Final']

# print info

for hw, score in enumerate(homeworks):

print(f'Homework {hw}: {score}')


print(f'Midterm: {midterm}')

print(f'Final: {final}')

# Compute student total score

total_points = sum([i for i in homeworks]) +


midterm + final

print(f'Final percentage: {100*(total_points /


500.0):.1f}%')

user_input = input('Enter student name: ')

©zyBooks 01/03/22 22:13 1172417

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

zyDE 10.15.1: Nested dictionaries example: Music library.


LOUISVILLEMSBAPrep2DaviesWinter2022

The following example demonstrates a program that uses 3 levels of


nested dictionaries to create a simple music library.

The following program uses nested dictionaries to store a small music


library. Extend the program such that a user can add artists, albums,
and songs to the library. First, add a command that adds an artist
name to the music dictionary. Then add commands for adding albums
and songs. Take care to check that an artist exists in the dictionary
before adding an album, and that an album exists before adding a
song.

Pre-enter any input for program,


Load default template...
then press run.
 
1 music = {
2 'Pink Floyd': {
Run
3 'The Dark Side of
4 'songs': [ 'Sp
5 'year': 1973,
6 'platinum': Tr
7 },
8 'The Wall': {
9 'songs': [ 'An
10 'year': 1979,
11 'platinum': Tr
12 }
13 },
14 'Justin Bieber': {
15 'My World':{
16 'songs': ['One
17 'year': 2010,
©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

PARTICIPATION
ACTIVITY
10.15.1:
Nested dictionaries.

1) Nested dictionaries are a flexible way


to organize data.

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

2) Dictionaries can contain, at most, three


levels of nesting.
True
False ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

3) The expression {'D1': {'D2': LOUISVILLEMSBAPrep2DaviesWinter2022

'x'}} is valid.
True
False

10.16 String formatting using %

info This section has been set as optional by your instructor.

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)

The '%%' sequence displays an actual percentage sign character,©zyBooks


as in 01/03/22 22:13 1172417

print('Annual percentage rate is %f%%' % apr). Bharathi Byreddy

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

1. Simple string replacement can be done using the %s conversion specifier.


2. The %d specifier is used for integer replacement in a formatted string.
3. The %f specifier is used for float replacement in a formatted string.
If an integer is passed to a
floating-point specifier, the value becomes a float.

Table 10.16.1: Common conversion specifiers. ©zyBooks 01/03/22 22:13 1172417

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

Substitute as hexadecimal in lowercase (%x) print('%x'


%x, %X % 31)
1f
or uppercase (%X).

Substitute as floating-point exponential print('%E'


%e, %E % 15.2)
1.520000E+01
format in lowercase (%e) or uppercase (%E).

zyDE 10.16.1: Conversion specifiers automatically convert values.


The program below prints the average payday loan interest rate of
410.9 percent (not a typo; see Wikipedia: Payday loan). Try inputting the
integer 411 instead, noting how the type is converted by %f to 411.0.

410.9
©zyBooks 01/03/22 22:13 1172417

Load default template... Bharathi Byreddy


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

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

PARTICIPATION
ACTIVITY
10.16.2:
String formatting.

Complete the code using formatting specifiers to generate the described output.

1) Assume price = 150.

I saved $150!

print('I saved $ !' %


price)

Check Show answer

2) Assume percent = 40.

Buy now! Save 40%!

print('Buy now! Save !'


% percent)

Check Show answer

Multiple conversion specifiers

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

1) Assume item = 'burrito' and LOUISVILLEMSBAPrep2DaviesWinter2022


price = 5.

The burrito is $5

print('The is $%d' %
(item, price))

Check Show answer

2) Assume item = 'backpack' and


weight = 5.2.

The backpack is 5.200000 pounds.

print('The %s is
pounds.' % (item, weight))

Check Show answer

3) Assume city = 'Boston' and


distance = 2100.

We are 2100 miles from Boston.

print('We are %d miles from


%s.' % ( ))

Check Show answer

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

CHALLENGE LOUISVILLEMSBAPrep2DaviesWinter2022
ACTIVITY
10.16.1:
Printing a string.

Write a single statement to print: user_word,user_number. Note that there is no space


between the comma and user_number.

Sample output with inputs: 'Amy' 5

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

4 ''' Your solution goes here ''' LOUISVILLEMSBAPrep2DaviesWinter2022


5

Run

CHALLENGE
ACTIVITY
10.16.2:
String formatting.

368708.2344834.qx3zqy7

10.17 String formatting using format()

The format() method


©zyBooks
Program output commonly includes variables as a part of the text. 01/03/22
The string 22:13method
format() 1172417
allows
Bharathi Byreddy

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

parentheses. Bharathi Byreddy

2. The next replacement field uses the next value, and so on.
LOUISVILLEMSBAPrep2DaviesWinter2022

The three ways to provide values to replacements fields include:

Table 10.17.1: Three ways to format strings.

Replacement Formatted
Example
definition string result

Positional 'The {1} in the {0} is {2}.'.format('hat', 'cat', The cat in


'fat')
the hat is
replacement fat.

Inferred The cat in


'The {} in the {} is {}.'.format('cat', 'hat',
positional 'fat')
the hat is
fat.
replacement

'The {animal} in the {headwear} is


Named {shape}.'.format(animal='cat', headwear='hat',
The cat in
the hat is
replacement shape='fat')
fat.

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:

Animation captions: ©zyBooks 01/03/22 22:13 1172417

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.

Determine the output of the following code snippets.

1) print('April {},
{}'.format(22, 2020))

Check Show answer

2) date = 'April {}, {}'

print(date.format(22, 2020))

Check Show answer

3) date = 'April {}, {}'

print(date.format(22, 2020))

print(date.format(23, 2024))

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

Check Show answer LOUISVILLEMSBAPrep2DaviesWinter2022

4) print('{0}:{1}'.format(9, 43))

Check Show answer

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))

Check Show answer

6) print('Hi
{{{0}}}!'.format('Bilbo'))
©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

Check Show answer

7) month = 'April'

day = 22

print('Today is {month}
{0}'.format(day, month=month))

Check Show answer

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.

Table 10.17.2: Common formatting specification presentation types.

'
©zyBooks 01/03/22 22:13 1172417

Type Description Example Bharathi Byreddy


Output

LOUISVILLEMSBAPrep2DaviesWinter2022
String (default presentation '{:s}'.format('Aiden')

s Aiden
type - can be omitted)

d Decimal (integer values only) '{:d}'.format(4)


4

b Binary (integer values only) '{:b}'.format(4)


100

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 78/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

Hexadecimal in lowercase (x)


x, X and uppercase (X) (integer '{:x}'.format(15)
f
values only)

e Exponent notation '{:e}'.format(44)


4.400000e+01

©zyBooks 01/03/22 22:13 1172417

Fixed-point notation (6 places '{:f}'.format(4)


Bharathi Byreddy

f 4.000000
of precision) LOUISVILLEMSBAPrep2DaviesWinter2022

Fixed-point notation
.[precision]f (programmer-defined '{:.2f}'.format(4)
4.00
precision)

0[precision]d Leading 0 notation '{:03d}'.format(4)


004

PARTICIPATION
ACTIVITY
10.17.4:
Format specifications and presentation types.

Enter the most appropriate format specification to produce the desired output.

1) The value of num as a decimal


(base 10) integer: 31
num = 31

print('{: }'.format(num))

Check Show answer

2) The value of num as a hexadecimal


(base 16) integer: 1f
num = 31

print('{: }'.format(num))

Check Show answer ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
3) The value of num as a binary (base
2) integer: 11111

num = 31

print('{: }'.format(num))

Check Show answer

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 79/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

Referencing format() values correctly

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

format specifications, like fill and alignment, are provided in aLOUISVILLEMSBAPrep2DaviesWinter2022


later section.

Table 10.17.3: Referencing the correct format() values in replacement


fields.

Replacement
Example Output
type

Inferred Three $1.50


'{:s} ${:.2f} tacos is ${:.2f}
positional total'.format('Three', 1.50, 4.50)
tacos is $4.50
total
replacement

Positional '{0:s} ${2:.2f} tacos is ${1:.2f} Three $1.50


total'.format('Three', 4.50, 1.50)
tacos is $4.50
replacement total

'{cnt:s} ${cost:.2f} tacos is ${sum:.2f}


Named total'.format(cnt = 'Three', cost = 1.50, sum =
Three $1.50
tacos is $4.50
replacement 4.50)
total

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

'{b} + {a} = {c:.2f}'.format(a=25, b=50, c=75.009) '{} + {} = {}'.format(25, 50, 75)


LOUISVILLEMSBAPrep2DaviesWinter2022

'{1:} + {0:} = {2:}'.format(25, 50, 75) '{} + {} = {2}'.format(25, 50, 75)

'{:.1f} + {:.1f} = {:.2f}'.format(25, 50, 75)

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

25.0 + 50.0 = 75.00

50 + 25 = 75.01 ©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022
Error

Reset

CHALLENGE
ACTIVITY
10.17.1:
String Formatting.

368708.2344834.qx3zqy7

CHALLENGE
ACTIVITY
10.17.2:
Printing a string.

Write a single statement to print: user_word,user_number. Note that there is no space


between the comma and user_number.

Sample output with inputs: Amy 5

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

10.18 String formatting using dictionaries

info This section has been set as optional by your instructor.

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

gmt = time.gmtime() # Get current Greenwich Mean Time

print('Time is: {:02d}/{:02d}/{:04d} {:02d}:{:02d} {:02d} sec' \

.format(gmt.tm_mon, gmt.tm_mday, gmt.tm_year, gmt.tm_hour, gmt.tm_min,


gmt.tm_sec))

©zyBooks 01/03/22 22:13 1172417

Time is: 06/07/2013 20:16 24 sec


Bharathi Byreddy

...
LOUISVILLEMSBAPrep2DaviesWinter2022
Time is: 06/07/2013 20:16 28 sec

import time

gmt = time.gmtime() # Get current Greenwich Mean Time

print('Time is: %(month)02d/%(day)02d/%(year)04d %(hour)02d:%(min)02d %


(sec)02d sec' % \

'year': gmt.tm_year, 'month': gmt.tm_mon, 'day': gmt.tm_mday,

'hour': gmt.tm_hour, 'min': gmt.tm_min, 'sec': gmt.tm_sec

Time is: 06/07/2013 20:16 24 sec

...

Time is: 06/07/2013 20:16 28 sec

PARTICIPATION
ACTIVITY
10.18.2:
Mapping keys.

Complete the print statement to produce the given output using mapping keys.

1) "I need 12 lilies, 6 roses, and 18


tulips."
print ('I need %(lilies)d
lilies, %(roses)d roses, and %
(tulips)d tulips.' % {
})

Check Show answer ©zyBooks 01/03/22 22:13 1172417

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' % {
})

Check Show answer


https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 83/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

10.19 LAB: Warm up: People's weights (Lists)


©zyBooks 01/03/22 22:13 1172417

(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

Weights: [236.0, 89.5, 176.0, 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

Weights: [236.0, 89.5, 176.0, 166.3]


LOUISVILLEMSBAPrep2DaviesWinter2022

Average weight: 166.95

Max weight: 236.00

(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

kilogram is equal to 2.2 pounds. (3 pts)

Ex:

Enter a list location (1 - 4):

Weight in pounds: 176.00


©zyBooks 01/03/22 22:13 1172417

Weight in kilograms: 80.00


Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

(5) Sort the list's elements from least heavy to heaviest weight. (2 pts)

Ex:

Sorted list: [89.5, 166.3, 176.0, 236.0]

NaN.2344834.qx3zqy7

LAB
ACTIVITY 10.19.1:
LAB: Warm up: People's weights (Lists) 0/9

main.py Load default template...

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.

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

Run your program as often as you'd like, before submitting


LOUISVILLEMSBAPrep2DaviesWinter2022
Develop mode Submit mode
for grading. Below, type any needed input values in the first
box, then click Run program and observe the program's
output in the second box.
Enter program input (optional)
If your code requires input values, provide them here.

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

Program output displayed here

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

Coding trail of your work What is this? LOUISVILLEMSBAPrep2DaviesWinter2022


History of your effort will appear here once you begin working
on this zyLab.

10.20 LAB: Filter and sort a list


Write a program that gets a list of integers from input, and outputs non-negative integers in ascending
order (lowest to highest).
Ex: If the input is:

10 -7 4 39 -6 12 2

the output is:

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

©zyBooks 01/03/22 22:13 1172417

Run your program as often asBharathi Byreddy


you'd like,
submitting
before
Develop mode Submit mode LOUISVILLEMSBAPrep2DaviesWinter2022
for grading. Below, type any needed input values in the first
box, then click Run program and observe the program's
output in the second box.
Enter program input (optional)
If your code requires input values, provide them here.

trending_flat trending_flat
main.py
Run program Input (from above)
(Your program)
Outp

Program output displayed here

Coding trail of your work What is this?

History of your effort will appear here once you begin working
on this zyLab.

10.21 LAB: Contact list


A contact list is a place where you can store a specific contact with other associated information such
as a phone number, email address, birthday, etc. Write a program©zyBooks
that first01/03/22
takes in22:13
word1172417

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:

Joe 123-5432 Linda 983-4123 Frank 867-5309

Frank

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 87/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

the output is:

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...

1 ''' Type your code here. '''

Run your program as often as you'd like, before submitting


Develop mode Submit mode
for grading. Below, type any needed input values in the first
box, then click Run program and observe the program's
output in the second box.
Enter program input (optional)
If your code requires input values, provide them here.

trending_flat trending_flat
main.py
Run program Input (from above)
(Your program)
Outp

©zyBooks 01/03/22 22:13 1172417

Program output displayed here Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 88/89
1/3/22, 10:14 PM MSBA Prep 2: Python Prep home

Coding trail of your work What is this?

History of your effort will appear here once you begin working
on this zyLab.

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

©zyBooks 01/03/22 22:13 1172417

Bharathi Byreddy

LOUISVILLEMSBAPrep2DaviesWinter2022

https://learn.zybooks.com/zybook/LOUISVILLEMSBAPrep2DaviesWinter2022/chapter/10/print 89/89

You might also like