Objectives: LO-7.1, LO-7.2, LO-7.3, LO-7.4
Prerequisites: the Module 7 reading and
Lab 6
Time: about 2 hours
In this lab you change lists with their methods, keep a to-do list, predict and draw what
happens when two names share a list, fix functions that change their arguments by surprise,
write list comprehensions, and sort records with a key. As before, each exercise ends with a
check cell that prints passed or says what is wrong, and fails until you answer.
Setup¶
Run the next cell first. It prints the version of Python.
import sys
print("Python", sys.version.split()[0])1. Changing a list¶
Run the next cell, then add lines of your own: insert a task, remove one, and sort the
list. Print tasks after each change to see what it did.
tasks = ["write report", "email Sam", "buy milk"]
tasks.append("water plants")
print(tasks)
removed = tasks.pop()
print(removed, tasks)Exercise L7.1 (LO-7.1, ★, about 10 minutes)¶
Trace this code by hand, writing down the list after each line:
stack = [5, 3, 8]
stack.append(1)
stack.insert(1, 7)
last = stack.pop()
first = stack.pop(0)
stack.remove(3)
stack.append(first)
returned = stack.sort()Then set last, first, and returned to your predictions of their values, and final to
the list stack at the end.
last = ...
first = ...
returned = ...
final = ...assert last == 1, "pop() with no argument removes and returns the last item."
assert first == 5, "pop(0) removes and returns the first item at that moment."
assert returned is None, "Methods that change a list return None."
assert final == [5, 7, 8], (
f"stack ends as a different list from {final!r}. Write it down after every line."
)
print("passed")Exercise L7.2 (LO-7.1, ★★, about 20 minutes)¶
Write run_command(tasks, command), which carries out one command on the to-do list tasks. A
command is a word, a space, and a task, which may itself contain spaces:
"add TASK"adds the task at the end of the list, unless it is already on it."urgent TASK"puts the task first. If it is already on the list, it moves to the front."done TASK"removes the task. If it isn’t on the list, nothing happens.Any other command leaves the list as it is.
The function changes tasks itself and returns None, as sort does.
Hint 1
Split the command at its first space with find and two slices, as Lab 6’s email_domain did: the action is everything before the space, and the task everything after it.
Hint 2
in tells you whether a task is on the list. Moving a task to the front is remove and then insert(0, ...).
def run_command(tasks, command):
"""Carry out one add, urgent, or done command on the list tasks, changing it."""
...todo = ["write report", "buy milk"]
returned = run_command(todo, "add water plants")
assert returned is None, "run_command changes the list; it should return None."
assert todo == ["write report", "buy milk", "water plants"], "add puts the task at the end."
run_command(todo, "add buy milk")
assert todo.count("buy milk") == 1, "add mustn't add a task that is already on the list."
run_command(todo, "urgent pay rent")
assert todo[0] == "pay rent", "urgent puts a new task first."
run_command(todo, "done buy milk")
assert "buy milk" not in todo, "done removes the task."
run_command(todo, "urgent water plants")
assert todo == ["water plants", "pay rent", "write report"], (
f"urgent should move a task that is already there to the front; the list is {todo!r}."
)
run_command(todo, "done walk dog")
run_command(todo, "delete pay rent")
assert todo == ["water plants", "pay rent", "write report"], (
"done with a task that isn't there, or an unknown command, should change nothing."
)
print("passed")2. Aliasing¶
Exercise L7.3 (LO-7.2, ★★, about 20 minutes)¶
For each snippet, draw the names and the lists they refer to, as the reading does, and predict
what it prints. Set pA to pF to the lists you predict. Then check each one: paste the snippet
into a cell of your own, or into Python Tutor to
compare your drawing with its drawing.
A
a = [1, 2]
b = a
b.append(3)
print(a)B
a = [1, 2]
b = a
b = b + [3]
print(a)C
a = [1, 2]
b = a
b += [3]
print(a)D
def double_all(values):
for i in range(len(values)):
values[i] = values[i] * 2
def replace_all(values):
values = [0] * len(values)
data = [1, 2, 3]
double_all(data)
replace_all(data)
print(data)E
grid = [[1], [2]]
copy_of_grid = grid[:]
copy_of_grid[0].append(9)
copy_of_grid[1] = [7]
print(grid)F
row = [0, 0]
board = [row, row]
board[0][1] = 5
print(board)pA = ...
pB = ...
pC = ...
pD = ...
pE = ...
pF = ...a = [1, 2]
b = a
b.append(3)
assert pA == a, "A: b = a gives the same list a second name, and append changes that list."
a = [1, 2]
b = a
b = b + [3]
assert pB == a, "B: b + [3] builds a new list, and only b moves to it."
a = [1, 2]
b = a
b += [3]
assert pC == a, "C: on a list, += changes the list in place."
def double_all(values):
for i in range(len(values)):
values[i] = values[i] * 2
def replace_all(values):
values = [0] * len(values)
data = [1, 2, 3]
double_all(data)
replace_all(data)
assert pD == data, "D: one function changes the list; the other only moves its local name."
grid = [[1], [2]]
copy_of_grid = grid[:]
copy_of_grid[0].append(9)
copy_of_grid[1] = [7]
assert pE == grid, "E: a slice is a shallow copy, so the inner lists are shared."
row = [0, 0]
board = [row, row]
board[0][1] = 5
assert pF == board, "F: both items of board are the same list."
print("passed")Exercise L7.4 (LO-7.2, ★★, about 10 minutes)¶
Both of these functions surprise the code that calls them. Run the cell after them to see how, then rewrite both so they return a new list and leave their argument unchanged. The docstrings say what each should return.
def sorted_scores(scores):
"""Return a new list of the scores in order, lowest first."""
scores.sort()
return scores
def without_negatives(values):
"""Return a new list of the values that aren't negative, in their order."""
for value in values:
if value < 0:
values.remove(value)
return valuesmarks = [70, 55, 90]
print(sorted_scores(marks), marks)
readings = [-1, -2, 3, -4, 5]
print(without_negatives(readings), readings)marks = [70, 55, 90]
assert sorted_scores(marks) == [55, 70, 90], "sorted_scores should return the scores in order."
assert marks == [70, 55, 90], "sorted_scores changed the caller's list. Use sorted instead."
readings = [-1, -2, 3, -4, 5]
result = without_negatives(readings)
assert result == [3, 5], f"without_negatives([-1, -2, 3, -4, 5]) gave {result!r}, not [3, 5]."
assert readings == [-1, -2, 3, -4, 5], "without_negatives changed the caller's list."
assert without_negatives([]) == [], "With no values, return an empty list."
print("passed")3. List comprehensions¶
Run the next cell, then change the expression before for and the condition after if, and
run it again.
numbers = list(range(1, 11))
print([n * n for n in numbers])
print([n for n in numbers if n % 3 == 0])
print([str(n) + "!" for n in numbers if n > 7])Exercise L7.5 (LO-7.3, ★, about 10 minutes)¶
Rewrite each loop as a list comprehension that builds the same list, one line for each, in the
next cell. Then run the check straight after it: the check reads your cell, and fails if it
still uses append.
evens = []
for n in range(1, 21):
if n % 2 == 0:
evens.append(n)
shouted = []
for word in ["tea", "milk", "juice"]:
shouted.append(word.upper() + "!")
lengths = []
for word in "the quick brown fox".split():
lengths.append(len(word))evens = ...
shouted = ...
lengths = ...your_cell = In[-2]
assert evens == list(range(2, 21, 2)), "evens: the even numbers from 2 to 20."
assert shouted == ["TEA!", "MILK!", "JUICE!"], "shouted: each word in capitals, then !."
assert lengths == [3, 5, 5, 3], "lengths: the length of each word."
assert "append" not in your_cell, "Use list comprehensions, not append."
assert your_cell.count(" for ") >= 3, "Write each list as a comprehension, with for inside [...]."
print("passed")Exercise L7.6 (LO-7.3, ★★, about 10 minutes)¶
Here is a comprehension:
WORDS = ["apple", "fig", "banana", "kiwi", "cherry"]
short = [word[:3].upper() for word in WORDS if len(word) > 4]Predict short, and set predicted to it. Then write a loop with append that builds the same
list in short_loop, without a comprehension.
WORDS = ["apple", "fig", "banana", "kiwi", "cherry"]predicted = ...
short_loop = []short = [word[:3].upper() for word in WORDS if len(word) > 4]
assert predicted == short, "predicted: only words longer than 4 letters, first 3 letters, upper."
assert short_loop == short, f"short_loop is {short_loop!r}, but should equal the comprehension."
assert "append" in In[-2], "Build short_loop with a for loop and append."
print("passed")4. Tuples, zip, enumerate, and sorting¶
Run the next cell. It pairs names with scores, unpacks each pair, and numbers the lines. Then
change start=1, and try sorted(pairs) and sorted(pairs, reverse=True).
names = ["Ada", "Grace", "Alan"]
scores = [92, 88, 95]
pairs = list(zip(names, scores))
print(pairs)
for position, (name, score) in enumerate(pairs, start=1):
print(position, name, score)(name, score) in the for line unpacks the tuple that each pair is, while position gets the
number enumerate adds.
Exercise L7.7 (LO-7.4, ★★, about 15 minutes)¶
Write ranking_lines(names, scores), which returns a list of lines such as "1. Alan 95", best
score first, and in alphabetical order of name where scores are equal. names[i] scored
scores[i]. Use zip, sorted with a key, and enumerate.
Hint
Sort the (name, score) pairs with a key that returns (-score, name) for each pair, as the reading’s last example does, then number the sorted pairs with enumerate(..., start=1).
def ranking_lines(names, scores):
"""Return lines like "1. Alan 95", best score first, ties in order of name."""
...expected = ["1. Alan 95", "2. Ada 92", "3. Barbara 92", "4. Edsger 88", "5. Grace 88"]
got = ranking_lines(["Ada", "Grace", "Alan", "Edsger", "Barbara"], [92, 88, 95, 88, 92])
assert got == expected, f"Expected:\n{expected}\nbut got:\n{got}"
assert ranking_lines([], []) == [], "No names give no lines."
assert ranking_lines(["Zoe"], [1]) == ["1. Zoe 1"], "One name gives one line."
print("passed")Exercise L7.8 (LO-7.4, ★★, about 20 minutes)¶
BOOKS is a list of records made up for this lab: a title, an author, a year, and a number of
pages, in that order. Write five functions. None of them may change the list they are given.
by_year(books)returns the books in order of year, oldest first. Books from the same year stay in their original order.longest_first(books)returns the books in order of pages, most first.by_author_then_year(books)returns the books in order of author, and by year for each author.shortest_title(books)returns the title of the book with the fewest pages.titles_after(books, year)returns, as a list comprehension, the titles of the books published afteryear, in their original order.
BOOKS = [
("River Notes", "Okafor", 2019, 212),
("The Quiet Engine", "Lindqvist", 2008, 348),
("Salt and Signal", "Okafor", 2014, 290),
("A Map of Small Things", "Reyes", 2019, 176),
("Winter Arithmetic", "Lindqvist", 2021, 254),
("Lanterns", "Nakamura", 2008, 198),
]def by_year(books):
"""Return the books in order of year, oldest first."""
...original = list(BOOKS)
def titles(books):
return [book[0] for book in books]
assert titles(by_year(BOOKS)) == [
"The Quiet Engine", "Lanterns", "Salt and Signal", "River Notes", "A Map of Small Things",
"Winter Arithmetic",
], "by_year: sort by the year, index 2. Books of the same year keep their order."
assert titles(longest_first(BOOKS))[:2] == ["The Quiet Engine", "Salt and Signal"], (
"longest_first: sort by pages, index 3, most first."
)
assert titles(by_author_then_year(BOOKS)) == [
"The Quiet Engine", "Winter Arithmetic", "Lanterns", "Salt and Signal", "River Notes",
"A Map of Small Things",
], "by_author_then_year: a key of (author, year) sorts by author, then by year."
assert shortest_title(BOOKS) == "A Map of Small Things", "shortest_title: min with a key."
assert titles_after(BOOKS, 2014) == [
"River Notes", "A Map of Small Things", "Winter Arithmetic",
], "titles_after: years after 2014 only, in the original order."
assert titles_after(BOOKS, 2030) == [], "No book is from after 2030."
assert BOOKS == original, "One of your functions changed BOOKS. Use sorted, not sort."
print("passed")Exercise L7.9 (LO-7.4, ★, about 5 minutes)¶
For each kind of data, decide whether a tuple or a list suits it better, and set the variable to
"tuple" or "list":
c1: a color as its red, green, and blue amounts, such as(255, 128, 0)c2: the lines of a file, read one at a time and kept for laterc3: a latitude and longitude, used to look up a place in a dictionaryc4: a queue of print jobs, which grows and shrinks all dayc5: the month and day of a birthday
c1 = "..."
c2 = "..."
c3 = "..."
c4 = "..."
c5 = "..."assert c1 == "tuple", "c1: always three numbers, each with its own meaning."
assert c2 == "list", "c2: any number of lines, all the same kind, added as they are read."
assert c3 == "tuple", "c3: a dictionary key must not change (Module 8)."
assert c4 == "list", "c4: items are added and removed."
assert c5 == "tuple", "c5: a fixed pair of fields."
print("passed")Summary¶
In this lab you:
changed lists with
append,insert,pop,remove, andsort, and kept a to-do list;drew and predicted what happens when two names, a name and a parameter, or a list and its shallow copy share a list;
fixed functions that changed their arguments by surprise, so they return new lists instead;
rewrote loops as list comprehensions and a comprehension as a loop; and
used tuples,
zip,enumerate, andsortedwith keys to rank and sort records.
Next, the Module 7 practice gives you more exercises with answers.