These exercises practice what the Module 7 reading explained. They aren’t graded. Work each one on paper first, then check your answer, and only then run the code to confirm it. The answers are in the collapsed blocks; open one only after you have an answer of your own.
Worked example: tracing list methods¶
queue = ["Ana", "Ben"]
queue.append("Chen")
queue.insert(0, "Dara")
served = queue.pop(0)
queue.remove("Ben")
print(served, queue)appendputs"Chen"at the end:["Ana", "Ben", "Chen"].insert(0, ...)puts"Dara"before index 0:["Dara", "Ana", "Ben", "Chen"].pop(0)removes the first item and returns it, soservedis"Dara", and the list is["Ana", "Ben", "Chen"].remove("Ben")removes the item equal to"Ben", wherever it is:["Ana", "Chen"].
It prints Dara ['Ana', 'Chen'].
Exercise 7.1 (LO-7.1, ★, about 10 minutes)¶
What does this print?
letters = ["c", "a", "b"]
print(letters.append("d"))
print(letters)
print(sorted(letters, reverse=True))
print(letters.pop(1), letters)Answer
None
['c', 'a', 'b', 'd']
['d', 'c', 'b', 'a']
a ['c', 'b', 'd']append changes the list and returns None, which the first print shows. sorted returns a new list and leaves letters alone. In the last line, Python works out the arguments from left to right, so pop(1) removes "a" before the second argument, letters, is printed.
Exercise 7.2 (LO-7.1, ★★, about 15 minutes)¶
Write unique(items), which returns a new list of the items without repeats, each in the place it
first appeared: unique([3, 1, 3, 2, 1]) is [3, 1, 2].
Hint
Start with an empty result, and append each item only if it isn’t in the result yet.
Answer
def unique(items):
"""Return a new list of items without repeats, in order of first appearance."""
result = []
for item in items:
if item not in result:
result.append(item)
return resultIt works on any sequence: unique("banana") is ['b', 'a', 'n']. Each in looks through the whole result, so for long lists this is slow; Module 8 does the same job with a set, which answers in without looking through every item.
Worked example: a list passed to a function¶
def add_all(target, extra):
for item in extra:
target.append(item)
extra = []
mine = [1]
yours = [2, 3]
add_all(mine, yours)
print(mine, yours)Draw the names when add_all starts: target and mine point to one list, [1], and extra
and yours point to another, [2, 3]. The loop appends through target, so the list mine
refers to becomes [1, 2, 3]. extra = [] moves only the local name extra to a new list;
yours still points to [2, 3]. It prints [1, 2, 3] [2, 3].
Exercise 7.3 (LO-7.2, ★★★, about 15 minutes)¶
What does this print, and why? Then change add_item so that each call without items starts a
new list.
def add_item(item, items=[]):
items.append(item)
return items
print(add_item("a"))
print(add_item("b"))
print(add_item("c", []))
print(add_item("d"))Hint
When does Python make the default value []: each time the function is called, or once?
Answer
['a']
['a', 'b']
['c']
['a', 'b', 'd']Python makes a default value once, when the def statement runs, and every call that leaves out items gets that same list. The first call appends "a" to it, and the second call finds it still there. The third call passes a new list of its own, so it doesn’t touch the shared one. The usual fix is a default of None, and a new list made inside the function:
def add_item(item, items=None):
"""Append item to items, or to a new list, and return the list."""
if items is None:
items = []
items.append(item)
return itemsNumbers and strings as defaults are safe, because they can’t be changed.
Exercise 7.4 (LO-7.2, ★★, about 10 minutes)¶
Draw the names and lists, then predict the three lines this prints.
import copy
matrix = [[1, 2], [3, 4]]
alias = matrix
shallow = matrix[:]
deep = copy.deepcopy(matrix)
matrix[0][0] = 100
matrix.append([5, 6])
print(alias)
print(shallow)
print(deep)Answer
[[100, 2], [3, 4], [5, 6]]
[[100, 2], [3, 4]]
[[1, 2], [3, 4]]alias is the same list as matrix, so it sees both changes. shallow is a new outer list that shares the inner lists: it sees the change to matrix[0], but not the new row appended to the outer matrix. deep copied the inner lists too, so it sees neither change.
Worked example: from a loop to a comprehension¶
odd_squares = []
for n in range(1, 10):
if n % 2 == 1:
odd_squares.append(n * n)Take the parts in turn: the expression appended, n * n, goes first; then the for clause,
for n in range(1, 10); then the if clause, if n % 2 == 1:
odd_squares = [n * n for n in range(1, 10) if n % 2 == 1]
print(odd_squares)[1, 9, 25, 49, 81]Exercise 7.5 (LO-7.3, ★, about 10 minutes)¶
Given
celsius = [0, 12.5, 100], write a comprehension for the same temperatures in Fahrenheit (c * 9 / 5 + 32).Given a list
words, write a comprehension for the words that start with a vowel, in either case.Rewrite this comprehension as a loop, and say what list it builds:
[n for n in range(100) if n % 7 == 0 and n % 2 == 1].
Answer
[c * 9 / 5 + 32 for c in celsius]is[32.0, 54.5, 212.0].[word for word in words if word[0].lower() in "aeiou"]. For["apple", "Echo", "kiwi", "orange", "umbrella", "tree"]it gives['apple', 'Echo', 'orange', 'umbrella']. An empty string inwordswould makeword[0]anIndexError;word[:1].lower()avoids that, but then"" in "aeiou"isTrue, so addword != "" andto the condition.result = [] for n in range(100): if n % 7 == 0 and n % 2 == 1: result.append(n)It builds the odd multiples of 7 below 100:
[7, 21, 35, 49, 63, 77, 91].
Exercise 7.6 (LO-7.3, ★★, about 15 minutes)¶
A comprehension’s expression can be another comprehension:
table = [[row * column for column in range(1, 4)] for row in range(1, 4)]Predict
table.Write a comprehension for the sum of each column of
table.Explain why
[[0] * 3 for row in range(3)]doesn’t fall into the repeated-row trap that[[0] * 3] * 3does.
Hint
The inner comprehension builds one row; the outer one runs it once for each row. For column i, the items are row[i] for each row of the table.
Answer
[[1, 2, 3], [2, 4, 6], [3, 6, 9]].[sum([row[i] for row in table]) for i in range(3)]is[6, 12, 18].The comprehension runs its expression,
[0] * 3, once for eachrow, so it builds three separate lists.[[0] * 3] * 3builds one list and repeats a reference to it three times.
Exercise 7.7 (LO-7.4, ★★, about 15 minutes)¶
Write stats(values), which returns a tuple of three things: how many values there are, their
total, and their average. For an empty list, return (0, 0, None). Then unpack its result for
[4, 8, 6] into three names, and print them.
Answer
def stats(values):
"""Return (count, total, average) of values; the average is None for no values."""
if len(values) == 0:
return 0, 0, None
total = sum(values)
return len(values), total, total / len(values)
count, total, average = stats([4, 8, 6])
print(count, total, average)It prints 3 18 6.0. return a, b, c returns one tuple, and unpacking it gives each value a name. Returning None for the average of no values, instead of dividing by zero, lets the caller check if average is None.
Exercise 7.8 (LO-7.4, ★★★, about 20 minutes)¶
Each record is a student’s name, grade, and year of graduation:
students = [("Kofi", "B", 2027), ("Ana", "A", 2026), ("Mei", "B", 2026), ("Lars", "A", 2027)]Sort the students by grade, with A first, then by year, then by name.
Sort them by year, latest first, and by name, A to Z, within each year.
Explain why each record is a tuple and the collection of records is a list.
Hint
A key that returns a tuple sorts by its first item, then its second. To reverse one part of the order but not another, negate the number.
Answer
sorted(students, key=lambda student: (student[1], student[2], student[0]))gives Ana, Lars, Mei, and Kofi:"A"comes before"B"by code point, so noreverseis needed.sorted(students, key=lambda student: (-student[2], student[0]))gives Kofi, Lars, Ana, and Mei. Two stable sorts do the same thing: sort by name first, then by year withreverse=True. The second sort keeps the names in order within each year, because a stable sort never reorders items with equal keys, even withreverse=True.A record always has three fields, each with its own meaning, so its size and the meaning of each position are fixed: a tuple. The class has any number of students, all the same kind of thing, and you sort it and may add to it: a list.