Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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.

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.

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.

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

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)

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.

3. List comprehensions

Run the next cell, then change the expression before for and the condition after if, and run it again.

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

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.

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

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

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.

  1. by_year(books) returns the books in order of year, oldest first. Books from the same year stay in their original order.

  2. longest_first(books) returns the books in order of pages, most first.

  3. by_author_then_year(books) returns the books in order of author, and by year for each author.

  4. shortest_title(books) returns the title of the book with the fewest pages.

  5. titles_after(books, year) returns, as a list comprehension, the titles of the books published after year, in their original order.

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 later

  • c3: a latitude and longitude, used to look up a place in a dictionary

  • c4: a queue of print jobs, which grows and shrinks all day

  • c5: the month and day of a birthday

Summary

In this lab you:

  • changed lists with append, insert, pop, remove, and sort, 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, and sorted with keys to rank and sort records.

Next, the Module 7 practice gives you more exercises with answers.