---
title: "Tuples, Sets and Comprehensions"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 2
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/2-tuples-sets-and-comprehensions
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 2 — Tuples, Sets and Comprehensions

Dara and Umar both borrow books from the town library, and they wonder whether they have the same taste. The library’s records give each of them a list of loans; a book borrowed twice appears twice. To answer “which books have we both read?” with lists, one has to take each book of Dara’s list and look for it along the whole of Umar’s, and then remove the repeats from the answer.

Python has a type made for this question, the *[set](#def-g10-tuples-sets-comprehensions-set)*, where a book is either in or out and never twice. This chapter introduces it, together with the *[tuple](#def-g10-tuples-sets-comprehensions-tuple)*, a fixed group of values such as a point $(3, 4)$, and the *[comprehension](#def-g10-tuples-sets-comprehensions-comprehension)*, a one-line way to build a list, a [set](#def-g10-tuples-sets-comprehensions-set) or a dictionary. On the way it answers a question that caused a bug in the previous chapter: why does a function that sorts its argument change the caller’s list?

**You already know.**

A list holds values in order, `t[i]` reads the value at position `i`, and `t.append(x)` adds `x` at the end (Book 1, grade 7). A dictionary maps keys to values, `d[k]`, and a record of a table is a dictionary from column names to values (Book 1, grade 8). The town library’s tables were met in Book 1; they are read here with `town.load("loans")`, which returns a list of such records. [Sets](#def-g10-tuples-sets-comprehensions-set) as mathematical objects belong to the mathematics book; this chapter is about the Python type.

## 2.1 Tuples

**Definition 2.1 (Tuple, unpacking).**

A *tuple* is a sequence of values written between parentheses and separated by commas, such as `(3, 4)`. Like a list it has a length and positions, read with `p[i]`; unlike a list, it cannot be changed once built. *Unpacking* assigns the values of a tuple to as many names at once: `x, y = p`.

```python
point = (3, 4)
print(point, point[0], len(point))

x, y = point
print("x =", x, "y =", y)

a = 1
b = 2
a, b = b, a
print("a =", a, "b =", b)

single = (7,)
not_a_tuple = (7)
print(single, type(single), not_a_tuple, type(not_a_tuple))
```

***Listing 2.1.** Building, reading and [unpacking](#def-g10-tuples-sets-comprehensions-tuple) [tuples](#def-g10-tuples-sets-comprehensions-tuple). code/grade-10/02-tuples-sets-comprehensions/listings/tuples.py*

```
$ python tuples.py
(3, 4) 3 2
x = 3 y = 4
a = 2 b = 1
(7,) <class 'tuple'> 7 <class 'int'>
```

***Output 2.1.** A [tuple](#def-g10-tuples-sets-comprehensions-tuple) of one element needs a comma; without it the parentheses are only grouping.*

Line 9 is the classic use of [unpacking](#def-g10-tuples-sets-comprehensions-tuple): the right side `b, a` builds the [tuple](#def-g10-tuples-sets-comprehensions-tuple) `(2, 1)` first, and only then are its two values given to `a` and `b`. No third variable is needed to swap two values.

The most common use of a [tuple](#def-g10-tuples-sets-comprehensions-tuple) is to return several results from one function. Strictly, a function still returns one value, a [tuple](#def-g10-tuples-sets-comprehensions-tuple); the caller unpacks it.

```python
def min_max(t):
    """Return the smallest and the largest number of the non-empty list t."""
    smallest = t[0]
    largest = t[0]
    for x in t:
        if x < smallest:
            smallest = x
        if x > largest:
            largest = x
    return smallest, largest


low, high = min_max([12, 18, 7, 15, 9])
print("lowest", low, "highest", high)
print(min_max([5]))
```

***Listing 2.2.** One loop, two results, returned as a [tuple](#def-g10-tuples-sets-comprehensions-tuple). code/grade-10/02-tuples-sets-comprehensions/listings/min_max.py*

```
$ python min_max.py
lowest 7 highest 18
(5, 5)
```

***Output 2.2.** The second call prints the [tuple](#def-g10-tuples-sets-comprehensions-tuple) itself.*

A [tuple](#def-g10-tuples-sets-comprehensions-tuple) whose positions have fixed meanings (a title, an author, a year) is a record. Numbers are easy to mix up; names are not.

**Definition 2.2 (Named tuple).**

A *named tuple* is a [tuple](#def-g10-tuples-sets-comprehensions-tuple) whose positions also have names, so that `b.year` and `b[2]` read the same value. In Python, `namedtuple("Book", ["title", "author", "year"])`, from the module `collections`, creates a new type `Book` of such [tuples](#def-g10-tuples-sets-comprehensions-tuple).

```python
from collections import namedtuple

Book = namedtuple("Book", ["title", "author", "year"])

b = Book("The Silent Code", "Fatou Dalewell", 2002)
print(b)
print(b.title, "was published in", b.year)
print(b[2] == b.year)
title, author, year = b
print(author)
```

***Listing 2.3.** A record of the town library as a [named tuple](#def-g10-tuples-sets-comprehensions-named-tuple). code/grade-10/02-tuples-sets-comprehensions/listings/named.py*

```
$ python named.py
Book(title='The Silent Code', author='Fatou Dalewell', year=2002)
The Silent Code was published in 2002
True
Fatou Dalewell
```

***Output 2.3.** A [named tuple](#def-g10-tuples-sets-comprehensions-named-tuple) prints its field names, and still unpacks like any [tuple](#def-g10-tuples-sets-comprehensions-tuple).*

A dictionary could hold the same record. The [named tuple](#def-g10-tuples-sets-comprehensions-named-tuple) is fixed: it always has the same three fields and they cannot be changed, which is what a record read from a table usually needs.

## 2.2 Mutable and immutable values

**Definition 2.3 (Mutable, immutable).**

A value is *mutable* when it can be changed after it is built, and *immutable* when it cannot. Lists, dictionaries and [sets](#def-g10-tuples-sets-comprehensions-set) are mutable. Numbers, strings and [tuples](#def-g10-tuples-sets-comprehensions-tuple) are immutable: an operation on them builds a new value.

```python
scores = [12, 18, 7]
scores[0] = 13
print(scores)

point = (3, 4)
point[0] = 5
print(point)
```

***Listing 2.4.** The same assignment on a list and on a [tuple](#def-g10-tuples-sets-comprehensions-tuple). code/grade-10/02-tuples-sets-comprehensions/listings/immutable.py*

```
$ python immutable.py
[13, 18, 7]
Traceback (most recent call last):
  File "immutable.py", line 6, in <module>
    point[0] = 5
    ~~~~~^^^
TypeError: 'tuple' object does not support item assignment
[exit status 1]
```

***Output 2.4.** Changing a position of a [tuple](#def-g10-tuples-sets-comprehensions-tuple) is refused.*

The difference matters because of the way Python names values. A variable does not contain a list; it *refers* to a list stored somewhere in memory. The assignment `b = a` does not copy anything: it makes `b` refer to the same list as `a`.

**Definition 2.4 (Alias).**

Two names are *aliases* when they refer to the same value in memory. The test `a is b` is true exactly when `a` and `b` are aliases; the test `a == b` compares the contents of two values, which may be distinct.

```python
a = [1, 2, 3]
b = a
b.append(4)
print("a:", a, " b:", b, " a is b:", a is b)

c = list(a)
c.append(5)
print("a:", a, " c:", c, " a is c:", a is c)
print("a == [1, 2, 3, 4]:", a == [1, 2, 3, 4])
```

***Listing 2.5.** An [alias](#def-g10-tuples-sets-comprehensions-alias) and a copy. code/grade-10/02-tuples-sets-comprehensions/listings/alias.py*

```
$ python alias.py
a: [1, 2, 3, 4]  b: [1, 2, 3, 4]  a is b: True
a: [1, 2, 3, 4]  c: [1, 2, 3, 4, 5]  a is c: False
a == [1, 2, 3, 4]: True
```

***Output 2.5.** A change made through `b` is seen through `a`; a change made to the copy `c` is not.*

The figure below draws the memory after line 7: names on the left, values on the right, an arrow for “refers to”.

![Names refer to values. a and b are aliases of one list; c refers to a copy, which changes on its own.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-tuples-sets-comprehensions/fig-164b6a8ade97.svg)

*Names refer to values. `a` and `b` are [aliases](#def-g10-tuples-sets-comprehensions-alias) of one list; `c` refers to a copy, which changes on its own.*

This explains the bug of the previous chapter: inside `largest_three(t)`, the parameter `t` is an [alias](#def-g10-tuples-sets-comprehensions-alias) of the caller’s list, so `t.sort()` sorts the caller’s list. [Aliases](#def-g10-tuples-sets-comprehensions-alias) of an [immutable](#def-g10-tuples-sets-comprehensions-mutable) value are harmless, since nobody can change it; [aliases](#def-g10-tuples-sets-comprehensions-alias) of a [mutable](#def-g10-tuples-sets-comprehensions-mutable) value are where [side effects](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-side-effect) come from.

A copy made by `list(a)`, or by the slice `a[:]`, is a new list holding the same elements. When those elements are themselves lists, they are not copied: the new outer list refers to the same inner lists.

**Definition 2.5 (Shallow copy, deep copy).**

A *shallow copy* of a value is a new value whose parts refer to the same objects as the parts of the original. A *deep copy* copies the parts too, and their parts, all the way down, so that it shares nothing [mutable](#def-g10-tuples-sets-comprehensions-mutable) with the original. In Python, `list(a)` and `a[:]` make shallow copies, and `copy.deepcopy(a)` makes a deep copy.

```python
import copy

grid = [[0, 0, 0], [0, 0, 0]]
shallow = list(grid)
deep = copy.deepcopy(grid)

shallow[0][0] = 9
deep[1][2] = 7
print("grid:   ", grid)
print("shallow:", shallow)
print("deep:   ", deep)
print(shallow[0] is grid[0], deep[0] is grid[0])
```

***Listing 2.6.** A grid of two rows, copied two ways. code/grade-10/02-tuples-sets-comprehensions/listings/copy_nested.py*

```
$ python copy_nested.py
grid:    [[9, 0, 0], [0, 0, 0]]
shallow: [[9, 0, 0], [0, 0, 0]]
deep:    [[0, 0, 0], [0, 0, 7]]
True False
```

***Output 2.6.** The change through the [shallow copy](#def-g10-tuples-sets-comprehensions-copy) reaches the original grid.*

![After the listing: grid and its shallow copy are two outer lists sharing the same two rows, so the 9 written through shallow is seen through grid; the deep copy has rows of its own.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-tuples-sets-comprehensions/fig-b563bb3ff29a.svg)

*After the listing: `grid` and its [shallow copy](#def-g10-tuples-sets-comprehensions-copy) are two outer lists sharing the same two rows, so the `9` written through `shallow` is seen through `grid`; the [deep copy](#def-g10-tuples-sets-comprehensions-copy) has rows of its own.*

## 2.3 Sets

**Definition 2.6 (Set (Python type)).**

A *set* is a collection of values without order and without repeats. It is written between braces, `{1, 2, 3}`, or built from any sequence with `set(t)`; the empty set is `set()`, since `{}` is an empty dictionary. The test `x in s` says whether `x` belongs to `s`, `s.add(x)` adds an element, and the operators `&`, `|` and `-` give the intersection, the union and the difference of two sets.

```python
genres_ana = set(["mystery", "sport", "history", "mystery"])
genres_ben = {"poetry", "sport", "science"}

print(genres_ana)
print(len(genres_ana), "sport" in genres_ana, "poetry" in genres_ana)
print("both:  ", genres_ana & genres_ben)
print("either:", genres_ana | genres_ben)
print("only Ana:", genres_ana - genres_ben)

seen = set()
for word in ["to", "be", "or", "not", "to", "be"]:
    seen.add(word)
print(len(seen), "different words")
```

***Listing 2.7.** The genres two readers like, as [sets](#def-g10-tuples-sets-comprehensions-set). code/grade-10/02-tuples-sets-comprehensions/listings/sets.py*

```
$ python sets.py
{'history', 'mystery', 'sport'}
3 True False
both:   {'sport'}
either: {'history', 'mystery', 'poetry', 'science', 'sport'}
only Ana: {'history', 'mystery'}
4 different words
```

***Output 2.7.** The repeated `"mystery"` is kept once; the order in which a [set](#def-g10-tuples-sets-comprehensions-set) prints is Python’s choice.*

Two properties of [sets](#def-g10-tuples-sets-comprehensions-set) are worth keeping in mind. First, a [set](#def-g10-tuples-sets-comprehensions-set) has no positions: `s[0]` is an error, and the order in which a [set](#def-g10-tuples-sets-comprehensions-set) of strings prints can differ from one computer to another. To print a [set](#def-g10-tuples-sets-comprehensions-set) in a fixed order, print `sorted(s)`, which is a list. Second, the test `x in s` is fast, whatever the size of the [set](#def-g10-tuples-sets-comprehensions-set), whereas `x in t` on a list compares `x` with the elements one by one; grade 11 measures the difference.

The elements of a [set](#def-g10-tuples-sets-comprehensions-set), like the keys of a dictionary, must be [immutable](#def-g10-tuples-sets-comprehensions-mutable): Python files each element by a number computed from its value, and that number would be wrong if the value could change afterwards. A [tuple](#def-g10-tuples-sets-comprehensions-tuple) can be such a key; a list cannot.

```python
walls = {(0, 1): "wall", (2, 3): "door"}
print(walls[(2, 3)])
print((0, 1) in walls, (1, 0) in walls)

walls[[4, 4]] = "window"
```

***Listing 2.8.** The cells of a maze, keyed by their coordinates. code/grade-10/02-tuples-sets-comprehensions/listings/tuple_key.py*

```
$ python tuple_key.py
door
True False
Traceback (most recent call last):
  File "tuple_key.py", line 5, in <module>
    walls[[4, 4]] = "window"
    ~~~~~^^^^^^^^
TypeError: unhashable type: 'list'
[exit status 1]
```

***Output 2.8.** Python calls a value that may serve as a key *hashable*; a list is not.*

Now the question of the introduction. The function below gathers the books one member borrowed into a [set](#def-g10-tuples-sets-comprehensions-set), so that a book borrowed twice counts once, and the operator `&` does the rest.

```python
import town

loans = town.load("loans")


def books_of(member):
    """Return the set of the ids of the books that member borrowed."""
    result = set()
    for loan in loans:
        if loan["member_id"] == member:
            result.add(loan["book_id"])
    return result


first = books_of(40)
second = books_of(55)
print("member 40:", sorted(first))
print("member 55:", sorted(second))
print("both:     ", sorted(first & second))
print("sizes:", len(first), len(second), len(first & second), len(first | second))
```

***Listing 2.9.** Which books have members 40 and 55 both borrowed? code/grade-10/02-tuples-sets-comprehensions/listings/shared_books.py*

```
$ python shared_books.py
member 40: [16, 29, 57, 62, 71, 75]
member 55: [9, 11, 16, 34, 46, 57, 60, 62, 71, 72, 75]
both:      [16, 57, 62, 71, 75]
sizes: 6 11 5 12
```

***Output 2.9.** Member 40 is Dara, member 55 is Umar.*

![The two members’ sets of books, with the counts printed by the run (the five shared books are 16, 57, 62, 71 and 75). The union holds 6 + 11 - 5 = 12 books: the shared ones would otherwise be counted twice.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-tuples-sets-comprehensions/fig-8a00090f2821.svg)

*The two members’ [sets](#def-g10-tuples-sets-comprehensions-set) of books, with the counts printed by the run (the five shared books are 16, 57, 62, 71 and 75). The union holds $6 + 11 - 5 = 12$ books: the shared ones would otherwise be counted twice.*

## 2.4 Comprehensions

Many loops build a new collection from an old one: the squares of a list of numbers, the even ones, the first letter of each word. Python has a shorter notation for them.

**Definition 2.7 (Comprehension).**

A *comprehension* is an expression that builds a list, a [set](#def-g10-tuples-sets-comprehensions-set) or a dictionary from a sequence: `[e for x in t]` is the list of the values of the expression `e` for each element `x` of `t`, in order; `[e for x in t if c]` keeps only the elements for which the condition `c` is true. With braces, `{e for x in t}` builds a [set](#def-g10-tuples-sets-comprehensions-set) and `{k: v for x in t}` a dictionary.

![A comprehension is read from the middle: the loop, then the condition, then the expression, which comes first in the writing. On the right, the loop it stands for.](https://one-course.com/images/onecourse/chapters/computer-science-2/g10-tuples-sets-comprehensions/fig-dead99f64e27.svg)

*A [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) is read from the middle: the loop, then the condition, then the expression, which comes first in the writing. On the right, the loop it stands for.*

```python
numbers = [4, 7, 10, 3, 8]

squares = [n * n for n in numbers]
evens = [n for n in numbers if n % 2 == 0]
print(squares)
print(evens)

words = ["map", "graph", "path", "grid", "maze"]
first_letters = {w[0] for w in words}
lengths = {w: len(w) for w in words}
print(sorted(first_letters))
print(lengths)

pairs = [(r, c) for r in range(2) for c in range(3)]
print(pairs)
```

***Listing 2.10.** List, [set](#def-g10-tuples-sets-comprehensions-set) and dictionary [comprehensions](#def-g10-tuples-sets-comprehensions-comprehension). code/grade-10/02-tuples-sets-comprehensions/listings/comprehensions.py*

```
$ python comprehensions.py
[16, 49, 100, 9, 64]
[4, 10, 8]
['g', 'm', 'p']
{'map': 3, 'graph': 5, 'path': 4, 'grid': 4, 'maze': 4}
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
```

***Output 2.10.** The last [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) has two `for`: the second varies fastest, as in two nested loops.*

The [set](#def-g10-tuples-sets-comprehensions-set) [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) on line 9 removes the repeated `m` and `g` by itself; the dictionary [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) on line 10 maps each word to its length.

**Example 2.8 (The books of a member, in one line).**

The function `books_of` of the town listing is the [set](#def-g10-tuples-sets-comprehensions-set) [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) `{loan["book_id"] for loan in loans if loan["member_id"] == member}`: for each loan, if it is the member’s, put its book in the [set](#def-g10-tuples-sets-comprehensions-set).

**Remark 2.9 (When a loop is clearer).**

A [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) is for building a collection and nothing else. When each step must also print, count, stop early (`break`) or update several variables, a loop is clearer; and a [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) that no longer fits on one line is usually better written as a loop. The test is the reader: if the [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) cannot be read aloud as one sentence, it should be a loop.

**Method 2.10 (Choosing a collection).**

1. A fixed group of values that belong together (a point, a date, a record): a [tuple](#def-g10-tuples-sets-comprehensions-tuple) or a [named tuple](#def-g10-tuples-sets-comprehensions-named-tuple) .
2. Values in an order that matters, possibly repeated, possibly changing: a list.
3. Membership questions (“is it there?”, “what is common?”) with no order and no repeats: a [set](#def-g10-tuples-sets-comprehensions-set) .
4. Values looked up by a key: a dictionary.

## 2.5 Exercises

**Exercise 2.1 ★.**

What do these lines print? `a, b, c = (1, 2, 3)`, then `a, c = c, a`, then `print(a, b, c)`. What happens with `x, y = (1, 2, 3)`?

**Solution of Exercise 2.1.**

After the first line `a`, `b`, `c` are $1$, $2$, $3$; the second line builds the [tuple](#def-g10-tuples-sets-comprehensions-tuple) `(3, 1)` and gives $3$ to `a` and $1$ to `c`: the line prints `3 2 1`. With `x, y = (1, 2, 3)` there are three values for two names: Python stops with `ValueError: too many values to unpack`.

**Exercise 2.2 ★.**

With `s = {1, 2, 3, 4}` and `t = {3, 4, 5}`, give `s & t`, `s | t`, `s - t`, `t - s`, `len(s | t)` and `5 in s`.

**Solution of Exercise 2.2.**

`s & t` is `{3, 4}`, `s | t` is `{1, 2, 3, 4, 5}`, `s - t` is `{1, 2}`, `t - s` is `{5}`, `len(s | t)` is $5$, and `5 in s` is `False`.

**Exercise 2.3 ★.**

Write a function `first_last(t)` that returns the first and the last element of a non-empty list as a [tuple](#def-g10-tuples-sets-comprehensions-tuple), with its specification, and a call that unpacks the result into two names.

**Solution of Exercise 2.3.**

`def first_last(t):` with the [docstring](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-docstring) “Return the first and the last element of t. [Precondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post): t is a non-empty list.” and the body `return t[0], t[-1]`. A call: `first, last = first_last([4, 8, 1])` gives `first` the value $4$ and `last` the value $1$. For a list of one element both are that element.

**Exercise 2.4 ★.**

What does this print? `t = [1, 2]`, `u = t`, `v = t[:]`, `u.append(3)`, `v.append(4)`, then `print(t, u, v, t is u, t is v, t == u)`. Draw the memory as in the figure on [aliases](#def-g10-tuples-sets-comprehensions-alias).

**Solution of Exercise 2.4.**

`u` is an [alias](#def-g10-tuples-sets-comprehensions-alias) of `t`; `v` is a copy. The line prints `[1, 2, 3] [1, 2, 3] [1, 2, 4] True False True`. The drawing has two lists: `t` and `u` point to `[1, 2, 3]`, `v` to `[1, 2, 4]`.

**Exercise 2.5 ★.**

Explain why `len(a | b) == len(a) + len(b) - len(a & b)` for any two [sets](#def-g10-tuples-sets-comprehensions-set), and check it on the run of the town listing. When is `len(a | b)` equal to `len(a) + len(b)`?

**Solution of Exercise 2.5.**

`len(a) + len(b)` counts every element of the union once, except those of the intersection, which belong to both [sets](#def-g10-tuples-sets-comprehensions-set) and are counted twice; subtracting `len(a & b)` counts them once. On the town run: $6 + 11 - 5 = 12$, the size printed for the union. The union has `len(a) + len(b)` elements exactly when `a & b` is empty.

**Exercise 2.6 ★★.**

A student writes `colours = ("red")` and then `for c in colours: print(c)`, hoping to print one colour. What does the loop print, and why? Correct the first line.

**Solution of Exercise 2.6.**

`("red")` is only the string `"red"` in parentheses, and a loop over a string goes through its characters: it prints `r`, `e`, `d` on three lines. The [tuple](#def-g10-tuples-sets-comprehensions-tuple) of one element is written `("red",)`, with the comma.

**Exercise 2.7 ★★.**

Write `common_books(loans, a, b)`, which returns the [set](#def-g10-tuples-sets-comprehensions-set) of the ids of the books borrowed both by member `a` and by member `b`, using two [set](#def-g10-tuples-sets-comprehensions-set) [comprehensions](#def-g10-tuples-sets-comprehensions-comprehension). Check it on members $40$ and $55$.

**Solution of Exercise 2.7.**

The file `exercises/common_books.py` builds the [set](#def-g10-tuples-sets-comprehensions-set) of the books of member `a` as

    `books_a = {loan["book_id"] for loan in loans if loan["member_id"] == a}`

and `books_b` the same way with `b`; the function returns `books_a & books_b`. For members $40$ and $55$ it returns `{16, 57, 62, 71, 75}`, as the town listing printed (checked by the chapter’s tests).

**Exercise 2.8 ★★.**

To make a $3 \times 3$ grid of zeros, a student writes `grid = [[0] * 3] * 3`, then `grid[0][0] = 1`, and prints `[[1, 0, 0], [1, 0, 0], [1, 0, 0]]`. Explain with a memory drawing, and build the grid with a [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) instead.

**Solution of Exercise 2.8.**

`[0] * 3` builds one list `[0, 0, 0]`; multiplying the outer list by $3$ repeats the *reference* to it, so the grid is an outer list of three arrows to the same row. Writing through `grid[0]` changes that row, which is also `grid[1]` and `grid[2]`. The [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) `[[0] * 3 for _ in range(3)]` evaluates `[0] * 3` three times and builds three rows (`exercises/grid_bug.py`).

**Exercise 2.9 ★★.**

What do these print? `{w: w.upper() for w in ["a", "b"]}`, then `{n % 3 for n in range(10)}`, then `{n: n * n for n in range(4) if n != 2}`.

**Solution of Exercise 2.9.**

`{"a": "A", "b": "B"}`; then the [set](#def-g10-tuples-sets-comprehensions-set) of the remainders, `{0, 1, 2}`; then `{0: 0, 1: 1, 3: 9}`, where the key $2$ is left out by the condition.

**Exercise 2.10 ★★.**

A [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) can list all the subsets of `["a", "b", "c", "d"]`. Without running it, how many are there? Explain the count by deciding, element by element, whether it is in or out, and say how many subsets have exactly two elements.

**Solution of Exercise 2.10.**

A subset is fixed by deciding, for each of the four elements, whether it is in or out: $2$ choices for `"a"`, times $2$ for `"b"`, and so on, so $2 \times 2 \times 2 \times 2 = 16$ subsets, from the empty [set](#def-g10-tuples-sets-comprehensions-set) to the whole [set](#def-g10-tuples-sets-comprehensions-set). The subsets of two elements are the pairs `ab`, `ac`, `ad`, `bc`, `bd`, `cd`: $6$. The [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) of `exercises/subsets.py` lists the $16$ (checked by the chapter’s tests).

**Exercise 2.11 ★★.**

Write `distinct_authors(books)`, which returns the [set](#def-g10-tuples-sets-comprehensions-set) of the authors of a list of book records, and `authors_in_genre(books, genre)`, which returns the sorted list of the authors of at least one book of the genre. How many distinct authors does the town library have?

**Solution of Exercise 2.11.**

The function `distinct_authors` is one [set](#def-g10-tuples-sets-comprehensions-set) [comprehension](#def-g10-tuples-sets-comprehensions-comprehension),

    `return {book["author"] for book in books}`

and `authors_in_genre` adds the condition `if book["genre"] == genre` to it and passes the [set](#def-g10-tuples-sets-comprehensions-set) to `sorted` (`exercises/distinct_authors.py`). The town library’s $80$ books have $23$ distinct authors.

**Exercise 2.12 ★★★.**

Without [sets](#def-g10-tuples-sets-comprehensions-set), the common books of two lists `a` and `b` are found by taking each element of `a` and comparing it with the elements of `b` one by one until a match is found. *(a)* What is the largest number of comparisons for lists of $6$ and $11$ books? *(b)* When is it reached? *(c)* For two lists of $n$ elements each, what is the largest number, and how does it change when $n$ doubles?

**Solution of Exercise 2.12.**

*(a)* Each of the $6$ elements of `a` is compared with at most the $11$ elements of `b`: at most $6 \times 11 = 66$ comparisons. *(b)* It is reached when no element of `a` is found before the end of `b`: for example when the lists have nothing in common. *(c)* $n \times n = n^2$; when $n$ doubles, the largest number is multiplied by $4$. With [sets](#def-g10-tuples-sets-comprehensions-set), `x in s` does not go through `s`, which is why the [set](#def-g10-tuples-sets-comprehensions-set) version is much faster on large lists (`exercises/count_intersection.py` counts the comparisons).

**Exercise 2.13 ★★★.**

Write `transpose(table)`, which returns the transpose of a rectangular list of rows (row $i$ of the result is column $i$ of the table), as a single nested [comprehension](#def-g10-tuples-sets-comprehensions-comprehension). Check that transposing twice gives back the table.

**Solution of Exercise 2.13.**

`return [[row[j] for row in table] for j in range(len(table[0]))]`: the outer [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) goes through the column numbers, the inner one collects the value of that column in each row. On `[[1, 2, 3], [4, 5, 6]]` it gives `[[1, 4], [2, 5], [3, 6]]`, and transposing that gives the table back (`exercises/transpose.py`).

**Exercise 2.14 ★★★.**

A game computes the next state of a grid of `0` and `1` by flipping every cell. Its function starts with `new = list(grid)` and writes `new[r][c] = 1 - grid[r][c]` for every cell. The game shows the right next state, but the previous state, kept by the caller for an “undo” button, has changed too. Find the cause and fix it.

**Solution of Exercise 2.14.**

`list(grid)` is a [shallow copy](#def-g10-tuples-sets-comprehensions-copy): `new` is a new outer list, but its rows are the rows of `grid`. Writing `new[r][c]` writes into the caller’s rows, so the “undo” state changes with the new one. The fix is a [deep copy](#def-g10-tuples-sets-comprehensions-copy), `new = copy.deepcopy(grid)`, or the [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) `new = [list(row) for row in grid]`, which copies each row (`exercises/grid_copy.py`; the tests check that the caller’s grid is untouched).

**Exercise 2.15 ★★★.**

The *Jaccard index* of two [sets](#def-g10-tuples-sets-comprehensions-set) $A$ and $B$, not both empty, is $|A \cap B| / |A \cup B|$: the share of their union that they have in common. Write `jaccard(a, b)`, which returns it as an exact fraction (`fractions.Fraction`), with an assertion on its [precondition](https://one-course.com/books/computer-science/2/en/chapter/1-specifications-assertions-and-tests#def-g10-specifications-and-tests-pre-post). What are its smallest and largest possible values, and when are they reached?

**Solution of Exercise 2.15.**

In `exercises/jaccard.py`: `assert a | b, "two empty sets have no Jaccard index"`, then `return Fraction(len(a & b), len(a | b))`. The intersection is part of the union, so the index lies between $0$ and $1$. It is $0$ when the [sets](#def-g10-tuples-sets-comprehensions-set) have no element in common, and $1$ when the intersection is the whole union, that is, when the two [sets](#def-g10-tuples-sets-comprehensions-set) are equal.

## 2.6 Problem: Readers Alike

**Problem 2.1.**

Weekend problem — which two members read most alike?

The town library wants to start a reading club and pair up members with similar tastes. It measures how alike two readers are with the Jaccard index of their [sets](#def-g10-tuples-sets-comprehensions-set) of borrowed books ([Exercise 2.15](#exo-g10-tuples-sets-comprehensions-15)). The program `exercises/readers_alike.py` of this chapter’s code does the computation; the questions follow it step by step.

**Part I — One set per member.**

1. The program builds a dictionary `books` from each member id to a [set](#def-g10-tuples-sets-comprehensions-set) of book ids, with `books.setdefault(m, set()).add(b)` . Explain what `setdefault` does here (look it up with `help(dict.setdefault)` ), and why a [set](#def-g10-tuples-sets-comprehensions-set) is used rather than a list.
2. The library recorded $400$ loans. Run the program: how many members borrowed at least one book, and how many different books were borrowed?
3. Why can the total of the sizes of the members’ [sets](#def-g10-tuples-sets-comprehensions-set) be smaller than $400$ ?
4. Write the dictionary `books` as a dictionary [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) whose values are [set](#def-g10-tuples-sets-comprehensions-set) [comprehensions](#def-g10-tuples-sets-comprehensions-comprehension) , and say why this version is slower than the loop of the program.

**Part II — Two members.**

5. From the run of the town listing, give the sizes of the [sets](#def-g10-tuples-sets-comprehensions-set) of members $40$ and $55$ , of their intersection and of their union.
6. Compute the Jaccard index of members $40$ and $55$ as a fraction, then as a decimal to three places.
7. Give the Jaccard index of a member with herself, and of two members with no book in common.
8. Member $32$ borrowed one book, member $47$ two, and they share one. Compute their index.

**Part III — All the pairs.**

9. The program lists the pairs with the [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) `[... for i in ids for j in ids if i < j]` . Why the condition `i < j` ?
10. How many pairs are there for $60$ members? Give the count as a formula in the number $n$ of members.
11. The pairs are sorted with the key `(-value, i, j)` . Explain how this [tuple](#def-g10-tuples-sets-comprehensions-tuple) orders them, and why the two last components are there.
12. Run the program. Which pair comes first among all $60$ members, and with which index?
13. Explain why this pair says little about taste.
14. The program then keeps only the members with at least $5$ books. How many members and how many pairs are left?

**Part IV — The closest readers.**

15. Which pair comes first among the members with at least $5$ books, and with which index?
16. Which pairs come next, and how far behind?
17. Show that the Jaccard index of a [set](#def-g10-tuples-sets-comprehensions-set) of $6$ elements and a [set](#def-g10-tuples-sets-comprehensions-set) of $11$ elements is at most $6/11$ , and say when it reaches that value. How far is the pair $40$ and $55$ from it?
18. How many comparisons of two [sets](#def-g10-tuples-sets-comprehensions-set) does the program make for the members with at least $5$ books?
19. Check the first place with a different method: `itertools.combinations(ids, 2)` lists the same pairs; take the `max` of the indices.
20. State the result: the two members whose borrowed books are most alike, with their index as a fraction and a decimal, and the number of books each borrowed.

**Solution of Problem 2.1.**

**1.** `books.setdefault(m, set())` returns `books[m]` if the key `m` is already there; otherwise it first stores an empty [set](#def-g10-tuples-sets-comprehensions-set) under `m` and returns it. Then `.add(b)` puts the book in that [set](#def-g10-tuples-sets-comprehensions-set). A [set](#def-g10-tuples-sets-comprehensions-set) is used because a book borrowed twice must count once, and because `&` and `|` are needed next.

**2.** $60$ members borrowed at least one book, and $80$ different books were borrowed.

**3.** A member who borrowed the same book twice has it once in her [set](#def-g10-tuples-sets-comprehensions-set). On the town data the sizes add up to $388$: twelve loans repeat a book already borrowed by the same member.

**4.** With `ids = {l["member_id"] for l in loans}`, the dictionary is `{m: {l["book_id"] for l in loans if l["member_id"] == m} for m in ids}`. For each of the $60$ members, the inner [comprehension](#def-g10-tuples-sets-comprehensions-comprehension) goes through all $400$ loans: $24{,}000$ steps instead of the $400$ of the loop.

**5.** Sizes $6$ and $11$; intersection $5$; union $12$.

**6.** $5/12 \approx 0.417$.

**7.** With herself: $1$, since a [set](#def-g10-tuples-sets-comprehensions-set) and itself have the same intersection and union. With no common book: $0$.

**8.** Intersection $1$, union $2$: the index is $1/2$.

**9.** Without it, each pair would appear twice (`i, j` and `j, i`), and each member would be paired with herself, with the index $1$.

**10.** Each of the $n$ members is paired with the $n - 1$ others, and each pair is then counted twice: $n(n-1)/2$ pairs, that is $60 \times 59 / 2 = 1{,}770$.

**11.** [Tuples](#def-g10-tuples-sets-comprehensions-tuple) compare position by position, like words in a dictionary. The first component is the index with a minus sign, so a larger index comes first; when two pairs have the same index, the member ids decide, so the order never depends on chance.

**12.** Members $32$ and $47$, with $1/2 = 0.500$.

**13.** It rests on one shared book: member $32$ borrowed a single book. With so few books, one coincidence gives a large index. Indices of very small [sets](#def-g10-tuples-sets-comprehensions-set) are not evidence of a common taste.

**14.** $49$ members and $49 \times 48 / 2 = 1{,}176$ pairs.

**15.** Members $40$ and $55$, with $5/12 \approx 0.417$.

**16.** Members $15$ and $56$, and members $31$ and $43$, both with $1/3 \approx 0.333$, about $0.08$ behind the first pair.

**17.** The intersection has at most $6$ elements (it is part of the smaller [set](#def-g10-tuples-sets-comprehensions-set)), and the union at least $11$ (it contains the larger one): the index is at most $6/11 \approx 0.545$. It reaches it exactly when the [set](#def-g10-tuples-sets-comprehensions-set) of $6$ is contained in the [set](#def-g10-tuples-sets-comprehensions-set) of $11$. The pair $40$ and $55$ misses it by one book: one of Dara’s six books is not among Umar’s.

**18.** One per pair: $1{,}176$.

**19.** The maximum over `itertools.combinations(ids, 2)` is again $5/12$ (checked by the chapter’s tests).

**20.** Among the members with at least $5$ books, the two who read most alike are Dara Reedfield (member $40$, $6$ books) and Umar Daleton (member $55$, $11$ books): they share $5$ books, and their Jaccard index is $5/12 \approx 0.417$, ahead of the next pairs at $1/3$.
