---
title: "Lists"
book: "Primary & Middle School Computer Science"
subject: computer-science
language: en
chapter: 20
exercises: 12
source: https://one-course.com/books/computer-science/1/en/chapter/20-lists
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 20 — Lists

The weather station at Hilltop, on the edge of the town, measures the rain every day. For January, that makes thirty-one numbers. A [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) could keep them in thirty-one [variables](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value), `day1`, `day2`, and so on to `day31`, but adding them up would take a line thirty-one names long, and the whole year would need 365 [variables](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value). Python keeps such numbers together, in order, under a single name.

**You already know.**

A `for` [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) repeats its block, and `range(n)` counts from 0 to $n - 1$ ([Chapter 16](https://one-course.com/books/computer-science/1/en/chapter/16-repeating-with-for-turtle-drawings#ch-g6-for-loops-turtle)). A [counter](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#def-g6-while-loops-counter) and a [running total](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#def-g6-while-loops-counter) start at 0 and grow at each turn ([Chapter 18](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#ch-g6-while-loops)). To find the largest card, keep the best one so far and compare it with each new card ([Chapter 10](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#ch-g4-algorithms-repeat-and-decide)).

## 20.1 A list holds many values in order

**Definition 20.1 (List, item, index, length).**

A *list* is a [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) that holds other [values](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) in order. It is written between square brackets, with commas: `[0.0, 0.7, 6.9]`. Each [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) is an *item* of the list. The position of an item is its *index*, counted from 0: `L[0]` is the first item, `L[1]` the second. The *length* of a list is its number of items, given by `len(L)`.

![A list is a row of cells. The indices, under the cells, run from 0 to len(rain) - 1 = 30.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-lists/fig-e833cece617e.svg)

*A [list](#def-g7-lists-list) is a row of cells. The indices, under the cells, run from 0 to $\texttt{len(rain)} - 1 = 30$.*

Here is the January [list](#def-g7-lists-list). A [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) in this chapter’s `figures` [folder](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-folder) wrote it from the town’s weather table, and a test checks that the two agree.

```python
# Rainfall at Hilltop, January 2025, in millimetres (day 1 first).
rain = [
    0.0, 0.0, 0.7, 0.0, 6.9, 0.0, 0.0, 0.0, 0.0, 3.3,
    0.0, 16.1, 0.0, 0.0, 5.9, 0.0, 3.3, 0.3, 7.7, 0.0,
    0.0, 2.8, 5.4, 0.0, 1.5, 0.0, 0.1, 0.0, 0.0, 2.3,
    0.0,
]
if __name__ == "__main__":
    print("days:", len(rain))
    print("1 January:", rain[0], "mm")
    print("12 January:", rain[11], "mm")
    print("31 January:", rain[len(rain) - 1], "mm")
```

***Listing 20.1.** January’s rainfall at Hilltop, in millimetres. code/grade-7/02-lists/listings/rain.py*

```
$ python rain.py
days: 31
1 January: 0.0 mm
12 January: 16.1 mm
31 January: 0.0 mm
```

***Output 20.1.** The first, the twelfth and the last day.*

The twelfth day has [index](#def-g7-lists-list) 11, and the last day [index](#def-g7-lists-list) 30, which is `len(rain) - 1`: an [index](#def-g7-lists-list) is always one less than the day’s number. Python also counts from the end with negative indices: `rain[-1]` is the last [item](#def-g7-lists-list). An [index](#def-g7-lists-list) past the end does not exist, and asking for it is an error:

```python
from rain import rain

print(rain[30])
print(rain[31])
```

***Listing 20.2.** [Index](#def-g7-lists-list) 31 of a [list](#def-g7-lists-list) of 31 [items](#def-g7-lists-list). code/grade-7/02-lists/listings/index_error.py*

```
$ python index_error.py
0.0
Traceback (most recent call last):
  File "~/session/index_error.py", line 4, in <module>
    print(rain[31])
          ~~~~^^^^
IndexError: list index out of range
[exit status 1]
```

***Output 20.2.** An `IndexError`: the indices stop at 30.*

The first line of [Listing 20.2](#lst-g7-lists-index-error) takes the [list](#def-g7-lists-list) from the [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) `rain.py`, as in the remark of [Chapter 19](https://one-course.com/books/computer-science/1/en/chapter/19-functions#ch-g7-functions).

## 20.2 Walking through a list

**Definition 20.2 (List traversal).**

A *list traversal*, or walk through a [list](#def-g7-lists-list), visits its [items](#def-g7-lists-list) one after another, from the first to the last. `for x in L:` runs its block once for each [item](#def-g7-lists-list), with `x` set to that [item](#def-g7-lists-list).

```python
week = [0.0, 0.0, 0.7, 0.0, 6.9, 0.0, 0.0]
for amount in week:
    print(amount, "mm")
```

***Listing 20.3.** A walk through one week. code/grade-7/02-lists/listings/walk.py*

```
$ python walk.py
0.0 mm
0.0 mm
0.7 mm
0.0 mm
6.9 mm
0.0 mm
0.0 mm
```

***Output 20.3.** One line per [item](#def-g7-lists-list), in order.*

When the position matters too, the walk goes over the indices with `range(len(L))`, and reads each [item](#def-g7-lists-list) as `L[i]`:

```python
week = [0.0, 0.0, 0.7, 0.0, 6.9, 0.0, 0.0]
for i in range(len(week)):
    if week[i] > 0:
        print("day", i + 1, "had", week[i], "mm")
```

***Listing 20.4.** A walk over the indices. code/grade-7/02-lists/listings/positions.py*

```
$ python positions.py
day 3 had 0.7 mm
day 5 had 6.9 mm
```

***Output 20.4.** [Index](#def-g7-lists-list) 2 is day 3, [index](#def-g7-lists-list) 4 is day 5.*

## 20.3 Appending and removing

A [list](#def-g7-lists-list) can change. A few [instructions](https://one-course.com/books/computer-science/1/en/chapter/2-instructions-in-order#def-g1-instructions-in-order-instruction), written after the [list](#def-g7-lists-list)’s name and a point, add or remove [items](#def-g7-lists-list).

```python
shopping = ["bread", "milk"]
print(shopping)
shopping.append("apples")       # add at the end
print(shopping)
shopping.insert(0, "eggs")      # add at index 0
print(shopping)
shopping.remove("milk")         # remove the first "milk"
print(shopping)
last = shopping.pop()           # remove the last item and give it back
print(last, shopping)
shopping[0] = "six eggs"        # replace the item at index 0
print(shopping)
```

***Listing 20.5.** A shopping [list](#def-g7-lists-list) that changes. code/grade-7/02-lists/listings/shopping.py*

```
$ python shopping.py
['bread', 'milk']
['bread', 'milk', 'apples']
['eggs', 'bread', 'milk', 'apples']
['eggs', 'bread', 'apples']
apples ['eggs', 'bread']
['six eggs', 'bread']
```

***Output 20.5.** The [list](#def-g7-lists-list) after each change.*

![Two of the changes, drawn without the remove, so that milk stays. insert(0, ...) puts a new item at index 0 and moves every other item one place along (their indices grow by 1); pop() takes away the last item.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-lists/fig-8d7e0a26bc2a.svg)

*Two of the changes, drawn without the `remove`, so that `milk` stays. `insert(0, ...)` puts a new [item](#def-g7-lists-list) at [index](#def-g7-lists-list) 0 and moves every other [item](#def-g7-lists-list) one place along (their indices grow by 1); `pop()` takes away the last [item](#def-g7-lists-list).*

With an [index](#def-g7-lists-list) in its brackets, `pop` takes away the [item](#def-g7-lists-list) at that [index](#def-g7-lists-list) instead: `pop(0)` takes the first [item](#def-g7-lists-list), and the others move one place back.

## 20.4 Computed by walking

Most questions about a [list](#def-g7-lists-list) are answered by one walk, with a [variable](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) that keeps what has been found so far: a [running total](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#def-g6-while-loops-counter), the largest [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) so far, or a [counter](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#def-g6-while-loops-counter) of the [items](#def-g7-lists-list) that pass a test.

```python
from rain import rain

total = 0
for amount in rain:
    total = total + amount
print("total:", round(total, 1), "mm")

largest = rain[0]
for amount in rain:
    if amount > largest:
        largest = amount
print("wettest day:", largest, "mm")

dry = 0
for amount in rain:
    if amount == 0:
        dry = dry + 1
print("dry days:", dry)
```

***Listing 20.6.** Three walks through January. code/grade-7/02-lists/listings/total_max_count.py*

```
$ python total_max_count.py
total: 56.3 mm
wettest day: 16.1 mm
dry days: 18
```

***Output 20.6.** The month’s rain, its wettest day and its dry days. `round(x, 1)` keeps one decimal.*

![A walk with a running total: above each item, the value of total once that item has been added.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-lists/fig-a9f41c8bbdaf.svg)

*A walk with a [running total](https://one-course.com/books/computer-science/1/en/chapter/18-repeating-with-while#def-g6-while-loops-counter): above each [item](#def-g7-lists-list), the [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of `total` once that [item](#def-g7-lists-list) has been added.*

To know *which* day was the wettest, the walk keeps the [index](#def-g7-lists-list) of the best [item](#def-g7-lists-list) so far rather than its [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value):

```python
from rain import rain

best = 0                        # the index of the largest value so far
for i in range(1, len(rain)):
    if rain[i] > rain[best]:
        best = i
print("wettest day: January", best + 1, "with", rain[best], "mm")
```

***Listing 20.7.** The position of the largest [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value). code/grade-7/02-lists/listings/position_of_max.py*

```
$ python position_of_max.py
wettest day: January 12 with 16.1 mm
```

***Output 20.7.** [Index](#def-g7-lists-list) 11: the twelfth of January.*

![January’s rainfall at Hilltop, drawn from the list of . The dry days have no bar.](https://one-course.com/images/onecourse/chapters/computer-science-1/g7-lists/fig-f23eeba7622c.svg)

*January’s rainfall at Hilltop, drawn from the [list](#def-g7-lists-list) of [Listing 20.1](#lst-g7-lists-rain). The dry days have no bar.*

## 20.5 A list is changed in place

`append`, `insert`, `remove` and `pop` do not make a new [list](#def-g7-lists-list): they change the [list](#def-g7-lists-list) itself. A [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) can therefore start with an empty [list](#def-g7-lists-list), `[]`, and fill it as it goes:

```python
readings = []
print(readings, len(readings))
for amount in [0.7, 6.9, 3.3]:
    readings.append(amount)
    print(readings, len(readings))
```

***Listing 20.8.** Filling an empty [list](#def-g7-lists-list). code/grade-7/02-lists/listings/in_place.py*

```
$ python in_place.py
[] 0
[0.7] 1
[0.7, 6.9] 2
[0.7, 6.9, 3.3] 3
```

***Output 20.8.** The same [list](#def-g7-lists-list) grows by one [item](#def-g7-lists-list) at each turn.*

## 20.6 Exercises

**Exercise 20.1 ★.**

With `L = [4, 8, 15, 16, 23, 42]`, what are `L[0]`, `L[2]`, `L[-1]` and `len(L)`?

**Solution of Exercise 20.1.**

`L[0]` is 4, `L[2]` is 15 (the third [item](#def-g7-lists-list)), `L[-1]` is 42 (the last [item](#def-g7-lists-list)) and `len(L)` is 6.

**Exercise 20.2 ★.**

What does this [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) print?

```python
numbers = [1, 2, 3]
numbers.append(4)
numbers.pop(0)
numbers.insert(1, 9)
print(numbers)
```

***Listing 20.9.** Three changes. code/grade-7/02-lists/exercises/three_ops.py*

**Solution of Exercise 20.2.**

`[1, 2, 3, 4]` after `append`, `[2, 3, 4]` after `pop(0)`, which removes the [item](#def-g7-lists-list) at [index](#def-g7-lists-list) 0, and `[2, 9, 3, 4]` after the `insert`. It prints `[2, 9, 3, 4]`.

**Exercise 20.3 ★.**

What does `for x in [3, 1, 4]: print(x * 2)` print?

**Solution of Exercise 20.3.**

6, 2 and 8, one per line.

**Exercise 20.4 ★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that prints the average daily rainfall of January at Hilltop.

**Solution of Exercise 20.4.**

```python
from rain import rain

total = 0
for amount in rain:
    total = total + amount
print("average:", round(total / len(rain), 2), "mm a day")
```

*The average daily rainfall. code/grade-7/02-lists/exercises/average.py*

It prints `average: 1.82 mm a day`: 56.3 millimetres in 31 days.

**Exercise 20.5 ★★.**

This [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) prints four numbers, then stops with an error. Why? Fix it.

```python
temps = [-3, -7, -1, -4]
for i in range(len(temps) + 1):
    print(temps[i])
```

***Listing 20.10.** One turn too many. code/grade-7/02-lists/exercises/off_by_one.py*

**Solution of Exercise 20.5.**

`range(len(temps) + 1)` counts 0, 1, 2, 3, 4, but the last [index](#def-g7-lists-list) of a [list](#def-g7-lists-list) of 4 [items](#def-g7-lists-list) is 3: `temps[4]` is an `IndexError`. The walk must use `range(len(temps))`, or simply `for t in temps:`.

**Exercise 20.6 ★★.**

This [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) should print the highest of four winter temperatures, all below zero. It prints 0. Why? Fix it.

```python
temps = [-3, -7, -1, -4]
largest = 0
for t in temps:
    if t > largest:
        largest = t
print(largest)
```

***Listing 20.11.** The largest of four temperatures? code/grade-7/02-lists/exercises/largest_bug.py*

**Solution of Exercise 20.6.**

`largest` starts at 0, which is higher than every temperature of the [list](#def-g7-lists-list): no [item](#def-g7-lists-list) is ever larger, and 0 stays. But 0 is not in the [list](#def-g7-lists-list)! The best so far must start with an [item](#def-g7-lists-list) of the [list](#def-g7-lists-list):

```python
temps = [-3, -7, -1, -4]
largest = temps[0]
for t in temps:
    if t > largest:
        largest = t
print(largest)
```

*Starting with the first [item](#def-g7-lists-list). code/grade-7/02-lists/exercises/largest_fixed.py*

It prints $-1$.

**Exercise 20.7 ★★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that counts the January days with some rain. Check that rainy days and dry days make 31 together.

**Solution of Exercise 20.7.**

```python
from rain import rain

rainy = 0
for amount in rain:
    if amount > 0:
        rainy = rainy + 1
print("rainy days:", rainy)
```

*Counting the rainy days. code/grade-7/02-lists/exercises/rainy_days.py*

It prints 13, and $13 + 18 = 31$: each day is either dry or rainy.

**Exercise 20.8 ★★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that builds a new [list](#def-g7-lists-list) with the January amounts above 5 millimetres, and prints it.

**Solution of Exercise 20.8.**

```python
from rain import rain

heavy = []
for amount in rain:
    if amount > 5:
        heavy.append(amount)
print(heavy)
```

*A new [list](#def-g7-lists-list) of the heavy days. code/grade-7/02-lists/exercises/above5.py*

It prints `[6.9, 16.1, 5.9, 7.7, 5.4]`.

**Exercise 20.9 ★★.**

How many [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) `amount > largest` does the second walk of [Listing 20.6](#lst-g7-lists-total-max-count) make? And how many [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) does [Listing 20.7](#lst-g7-lists-position-of-max) make? Why one fewer?

**Solution of Exercise 20.9.**

31 [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison): the walk goes through all 31 [items](#def-g7-lists-list), the first one included, which it compares with itself. [Listing 20.7](#lst-g7-lists-position-of-max) starts its walk at [index](#def-g7-lists-list) 1, since the [item](#def-g7-lists-list) at [index](#def-g7-lists-list) 0 is already the best so far: 30 [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison). For $n$ [items](#def-g7-lists-list), $n - 1$ [comparisons](https://one-course.com/books/computer-science/1/en/chapter/17-decisions-if-and-else#def-g6-if-else-comparison) are enough.

**Exercise 20.10 ★★★.**

Write a [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) that builds a [list](#def-g7-lists-list) with the [items](#def-g7-lists-list) of another [list](#def-g7-lists-list) in the opposite order, by walking through it once.

**Solution of Exercise 20.10.**

Each [item](#def-g7-lists-list) is inserted at the front, so the last one read ends up first:

```python
week = [0.0, 0.0, 0.7, 0.0, 6.9, 0.0, 0.3]
backwards = []
for amount in week:
    backwards.insert(0, amount)     # each new value goes in front
print(backwards)
```

*Reversing a [list](#def-g7-lists-list). code/grade-7/02-lists/exercises/reverse.py*

It prints `[0.3, 0.0, 6.9, 0.0, 0.7, 0.0, 0.0]`.

**Exercise 20.11 ★★★.**

Explain why the walk with `largest` always ends with the largest [value](https://one-course.com/books/computer-science/1/en/chapter/15-variables-and-input#def-g6-variables-and-input-value) of the [list](#def-g7-lists-list). Hint: say what `largest` holds after each turn.

**Solution of Exercise 20.11.**

Before the walk, `largest` is the first [item](#def-g7-lists-list): the largest of the [items](#def-g7-lists-list) seen so far, since only one has been seen. At each turn, if the new [item](#def-g7-lists-list) is larger, it replaces `largest`; if not, `largest` stays, and it is still at least as large as everything seen. So after each turn, `largest` is the largest of the [items](#def-g7-lists-list) seen so far. After the last turn, every [item](#def-g7-lists-list) has been seen: `largest` is the largest of the whole [list](#def-g7-lists-list).

**Exercise 20.12 ★★★.**

Write a [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `longest_equal_run(values)` that returns the [length](#def-g7-lists-list) of the longest run of equal neighbouring [items](#def-g7-lists-list): 3 for `[1, 2, 2, 2, 5, 5]`. Check it on a few examples, the empty [list](#def-g7-lists-list) among them.

**Solution of Exercise 20.12.**

The walk compares each [item](#def-g7-lists-list) with the one before it: `run` counts the equal neighbours up to the current [item](#def-g7-lists-list) and `longest` keeps the record. An empty [list](#def-g7-lists-list) has no run at all: it is the special case tested first, and the fourth check.

```python
def longest_equal_run(values):
    if len(values) == 0:
        return 0
    longest = 1
    run = 1
    for i in range(1, len(values)):
        if values[i] == values[i - 1]:
            run = run + 1
        else:
            run = 1
        if run > longest:
            longest = run
    return longest


print("expected 3, got", longest_equal_run([1, 2, 2, 2, 5, 5]))
print("expected 1, got", longest_equal_run([4, 3, 4]))
print("expected 4, got", longest_equal_run([7, 7, 7, 7]))
print("expected 0, got", longest_equal_run([]))
```

*The longest run of equal neighbours. code/grade-7/02-lists/exercises/longest_equal.py*

## 20.7 Problem: Dry Spells at Hilltop

**Problem 20.1.**

Weekend problem — the longest dry spell of the year

A *dry spell* is a run of days in a row with no rain at all. Gardeners and farmers watch them closely.

**Part I — By hand,** with the January [list](#def-g7-lists-list) of [Listing 20.1](#lst-g7-lists-rain).

1. Which day was the wettest, and how much rain fell?
2. How many days were dry?
3. Find the longest run of dry days in a row. On which day does it start?
4. How did you do it? Describe your method as a walk, with what you keep in your head at each day.

**Part II — A program for January.**

```python
from rain import rain

longest = 0
longest_end = 0
run = 0                          # dry days in a row, up to today
for i in range(len(rain)):
    if rain[i] == 0:
        run = run + 1
        if run > longest:
            longest = run
            longest_end = i
    else:
        run = 0
start = longest_end - longest + 1
print("longest dry run:", longest, "days, from January", start + 1)
```

***Listing 20.12.** The longest dry run of January. code/grade-7/02-lists/listings/dry_spell.py*

5. What does `run` hold after each day? Why is it set back to 0 on a rainy day?
6. Why does line 11 keep the [index](#def-g7-lists-list) of the *last* day of the run, and how does line 14 find its first day?
7. Run the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) . Does it agree with your answer to question 3?
8. If two dry runs have the same [length](#def-g7-lists-list) , which one does the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) report? Why?

**Part III — The whole year.** The [file](https://one-course.com/books/computer-science/1/en/chapter/7-files-and-folders#def-g3-files-and-folders-file) `hilltop_2025.py`, written by the same script, holds the rainfall of every day of 2025 in one [list](#def-g7-lists-list) of 365 [items](#def-g7-lists-list), and `month_days`, the number of days of each month.

```python
from hilltop_2025 import month_days, rain

names = ["January", "February", "March", "April", "May", "June", "July",
         "August", "September", "October", "November", "December"]


def date(day):
    """Day 0 of the year is 1 January; give the month and the day of the month."""
    month = 0
    while day >= month_days[month]:
        day = day - month_days[month]
        month = month + 1
    return f"{day + 1} {names[month]}"


longest = 0
longest_end = 0
run = 0
for i in range(len(rain)):
    if rain[i] == 0:
        run = run + 1
        if run > longest:
            longest = run
            longest_end = i
    else:
        run = 0
start = longest_end - longest + 1
print("days in 2025:", len(rain))
print("longest dry spell:", longest, "days")
print("from", date(start), "to", date(longest_end))
```

***Listing 20.13.** The longest dry spell of 2025. code/grade-7/02-lists/listings/dry_year.py*

9. The [function](https://one-course.com/books/computer-science/1/en/chapter/19-functions#def-g7-functions-function) `date` turns an [index](#def-g7-lists-list) of the year into a date. What does it return for the [index](#def-g7-lists-list) 0? For 31? For 58 and 59?
10. Run the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) . How long was the longest dry spell of 2025, and when was it?
11. Could the [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) find a dry spell that starts in one month and ends in the next? Why is it easier with one [list](#def-g7-lists-list) for the year than with twelve [lists](#def-g7-lists-list) , one per month?
12. State the result.

**Solution of Problem 20.1.**

**1.** The twelfth of January, with 16.1 millimetres.

**2.** 18 dry days (the [items](#def-g7-lists-list) equal to 0.0).

**3.** From the 6th to the 9th: 4 dry days in a row. The other runs are shorter: 2 days (1st and 2nd, 13th and 14th, 20th and 21st, 28th and 29th), or 1 day.

**4.** Walk through the days, keeping two numbers in mind: the [length](#def-g7-lists-list) of the dry run that ends today (one more than yesterday’s if today is dry, 0 if it rained) and the longest run met so far, with the day it ended.

**5.** `run` is the number of dry days in a row ending with the day just read. A rainy day breaks the run, so the count starts again from 0.

**6.** When `run` beats the record, the current day is the last day of the new longest run. The run has `longest` days and ends at [index](#def-g7-lists-list) `longest_end`, so it starts at `longest_end - longest + 1`.

**7.** It agrees: 4 days from the 6th of January.

```
$ python dry_spell.py
longest dry run: 4 days, from January 6
```

***Output 20.9.** January’s longest dry run.*

**8.** The first one: the record is beaten only by a strictly longer run (`run > longest`), so a run of the same [length](#def-g7-lists-list) does not replace it.

**9.** [Index](#def-g7-lists-list) 0 gives 1 January. For 31, the [loop](https://one-course.com/books/computer-science/1/en/chapter/10-algorithms-repeat-and-decide#def-g4-algorithms-repeat-and-decide-loop) takes away January’s 31 days: 1 February. For 58: $58 - 31 = 27$, less than 28, so 28 February; for 59: $59 - 31 - 28 = 0$, so 1 March.

**10.** The [program](https://one-course.com/books/computer-science/1/en/chapter/9-programs-and-the-operating-system#def-g4-programs-and-operating-system-program) prints the year’s result:

```
$ python dry_year.py
days in 2025: 365
longest dry spell: 11 days
from 10 August to 20 August
```

***Output 20.10.** The longest dry spell of 2025 at Hilltop.*

**11.** Yes: the year is one [list](#def-g7-lists-list), so a run simply goes on from the last day of a month to the first day of the next. With twelve [lists](#def-g7-lists-list), a walk would have to carry `run` from one [list](#def-g7-lists-list) into the next, and a run that crosses two months would be easy to cut in two by mistake.

**12.** **Result.** The longest dry spell of 2025 at Hilltop lasted 11 days, from 10 August to 20 August, as [Output 20.10](#out-g7-lists-dry-year) shows.
