---
title: Lists
heading: A whole set of readings in one name
eyebrow: A4 · Lesson 12 · Lists
xp: 40
---

::: hook
A meter logs a reading every second. A design sweep tries thirty resistor values. A parts bin holds every E12 value from 10 Ω to 1 MΩ. Each is a sequence of values you want to keep together, step through, sort, filter and summarize. Python's list does all of that, and it's also the stepping stone to NumPy arrays, which do the same things a hundred times faster.
:::

::: predict
## `x = [10, 20, 30, 40, 50]`. What is `x[1:3]`?

- [ ] `[10, 20, 30]`
- [x] `[20, 30]`
- [ ] `[20, 30, 40]`
- [ ] `20`

::: reveal
`[20, 30]`. Indexes start at 0, so `x[1]` is 20, and a slice `x[a:b]` stops *before* `b`, like `range`. The slice has `b - a` items.
:::
:::

::: nameit
## Making and reading lists

```
readings = [3.31, 3.29, 3.30, 3.35]
empty = []
```

| Code | Gives |
|---|---|
| `x[0]`, `x[-1]` | first, last |
| `x[1:3]` | items 1 and 2 |
| `x[:3]`, `x[-3:]` | first three, last three |
| `x[::2]` | every other item |
| `len(x)` | how many |
| `sum(x)`, `min(x)`, `max(x)` | total, smallest, largest |
| `v in x` | whether `v` is in it |
| `sorted(x)` | a sorted copy |

## Changing lists

Lists can be changed in place:

```
x.append(3.28)     # add to the end
x[0] = 3.30        # replace an item
x.pop()            # remove and return the last
x.sort()           # sort in place
```

**Copies and names.** `y = x` doesn't copy: both names refer to the same list, and changing one changes "both". Use `y = x.copy()` or `y = x[:]` for a real copy.

## Building lists

The loop-and-append pattern:

```
squares = []
for k in range(5):
    squares.append(k * k)
```

is so common that Python has a shorthand, the **list comprehension**:

```
squares = [k * k for k in range(5)]                 # [0, 1, 4, 9, 16]
big = [r for r in readings if r > 3.3]              # filter
volts = [float(s) for s in "3.3,5,12".split(",")]   # convert
```

## Statistics by hand

The mean is `sum(x) / len(x)`. The standard deviation measures the spread:

$$s = \sqrt{\frac{1}{n - 1}\sum_k (x_k - \bar x)^2}$$

which in Python is two lines:

```
m = sum(x) / len(x)
s = (sum((v - m)**2 for v in x) / (len(x) - 1)) ** 0.5
```

The $n - 1$ is for a sample from a larger population; A11 explains why.
:::

::: example
## Generate the E12 values from 10 Ω up to 82 kΩ.

::: solution
1. **Use a comprehension with two `for` parts.** Each decade from $10^1$ to $10^4$ multiplies each of the twelve mantissas.

```
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
values = [m * 10**d for d in range(1, 5) for m in E12]
print(len(values), values[0], values[-1])    # 48 10.0 82000.0
```

2. **Count them.** Four decades of twelve values make 48, from 10 Ω up to 82 kΩ.

**Answer:** one comprehension gives all 48 values, from 10 Ω to 82 kΩ.
:::
:::

::: example
## Find the E12 value closest to 3.6 kΩ.

::: solution
1. **Keep the closest value so far.** Walk through the list and replace `best` whenever a value is nearer the target.

```
target = 3600
best = values[0]
for v in values:
    if abs(v - target) < abs(best - target):
        best = v
print(best)     # 3300.0
```

2. **Settle the tie.** 3.3 kΩ is 300 Ω away and 3.9 kΩ is 300 Ω away too; the loop keeps the first one it finds when they tie.
3. **A shorter way.** Lesson 15 shows the one-line version with `min`.

**Answer:** 3.3 kΩ, which ties with 3.9 kΩ and comes first.
:::
:::

::: check
kind: python
given: n = 5..12 int; v0 = 3.3 | 5; d = 0.01 | 0.02

## Make a list `readings` of `n` = {n} values, where reading `k` is `v0 + d * k` (with `v0` = {v0}, `d` = {d}). Then set `mean` to their average and `last3` to the last three readings.

```python starter
readings = []
mean = 0
last3 = []
print(readings, mean, last3)
```

```python solution
readings = [v0 + d * k for k in range(n)]
mean = sum(readings) / len(readings)
last3 = readings[-3:]
print(readings, mean, last3)
```

```python tests
import math
assert len(readings) == n, f"readings should have {n} values."
assert math.isclose(readings[0], v0) and math.isclose(readings[-1], v0 + d * (n - 1)), "Reading k is v0 + d·k, for k = 0 to n − 1."
assert math.isclose(mean, v0 + d * (n - 1) / 2), "mean should be sum(readings) / len(readings)."
assert last3 == readings[-3:], "last3 should be readings[-3:]."
```

::: right
Right. A comprehension, `sum` over `len`, and a negative slice.
:::
:::

::: check
kind: python
given: t = 3.3 | 5 | 12; k = 4..9 int

## The list `x` (made for you) holds noisy readings. Set `above` to a list of the readings greater than `t` = {t}, and `count` to how many there are.

```python starter
x = [t + 0.1 * ((j * 37 + k) % 11 - 5) for j in range(20)]
above = x
count = 0
print(above, count)
```

```python solution
x = [t + 0.1 * ((j * 37 + k) % 11 - 5) for j in range(20)]
above = [v for v in x if v > t]
count = len(above)
print(above, count)
```

```python tests
xs = [t + 0.1 * ((j * 37 + k) % 11 - 5) for j in range(20)]
assert above == [v for v in xs if v > t], "above should keep only the readings greater than t, in their original order."
assert count == len(above), "count should be len(above)."
```

::: right
Right. A comprehension with an `if` filters in one line.
:::
:::

::: check
kind: python
given: k = 1..9 int

## Set `s` to the sample standard deviation of the list `x` (made for you), using the $n - 1$ formula.

```python starter
x = [10 + ((j * 7 + k) % 5) for j in range(12)]
s = 0
print(s)
```

```python solution
x = [10 + ((j * 7 + k) % 5) for j in range(12)]
m = sum(x) / len(x)
s = (sum((v - m)**2 for v in x) / (len(x) - 1)) ** 0.5
print(s)
```

```python tests
import statistics, math
xs = [10 + ((j * 7 + k) % 5) for j in range(12)]
assert math.isclose(s, statistics.stdev(xs)), "Use the n − 1 formula: the square root of the sum of squared deviations from the mean, over n − 1."
```

::: right
Right. That matches `statistics.stdev`, which you'll use from lesson 19 on.
:::
:::

::: check
kind: python
given: target = 1300 | 3600 | 5100 | 27000 | 61000

## Using the E12 list made for you, set `best` to the E12 value closest to `target` = {target} Ω.

```python starter
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
values = [m * 10**d for d in range(1, 6) for m in E12]
best = values[0]
print(best)
```

```python solution
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
values = [m * 10**d for d in range(1, 6) for m in E12]
best = values[0]
for v in values:
    if abs(v - target) < abs(best - target):
        best = v
print(best)
```

```python tests
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]
values = [m * 10**d for d in range(1, 6) for m in E12]
d = min(abs(v - target) for v in values)
assert abs(abs(best - target) - d) < 1e-9, f"best should be the value nearest {target}. Track the closest so far as you loop."
```

::: right
Right. The track-the-best pattern finds a minimum in one pass.
:::
:::

::: check
kind: python
given: k = 1..6 int; w = 3 | 4 | 5

## The starter makes `x`, a list of noisy readings. Set `smooth` to its `w`-point moving average ({w} points): entry `i` is the mean of `x[i]` through `x[i + w - 1]`, so `smooth` is `w - 1` entries shorter than `x`. Use a loop and slices, without NumPy.

```python starter
import random
random.seed(k)
x = [5 + random.uniform(-0.2, 0.2) for _ in range(20)]
smooth = []
for i in range(len(x)):
    smooth.append(x[i])
print(smooth)
```

```python solution
import random
random.seed(k)
x = [5 + random.uniform(-0.2, 0.2) for _ in range(20)]
smooth = []
for i in range(len(x) - w + 1):
    smooth.append(sum(x[i:i + w]) / w)
print(smooth)
```

```python tests
import random
random.seed(k)
xs = [5 + random.uniform(-0.2, 0.2) for _ in range(20)]
want = [sum(xs[i:i + w]) / w for i in range(len(xs) - w + 1)]
assert len(smooth) == len(xs) - w + 1, f"smooth should have {len(xs) - w + 1} entries: the window must fit inside the list."
assert all(abs(a - b) < 1e-12 for a, b in zip(smooth, want)), "Entry i is sum(x[i:i + w]) / w."
```

::: right
Right. The slice `x[i:i + w]` is exactly the window, and the last window starts at `len(x) - w`. A moving average trades a little delay for less noise.
:::
:::

::: check
kind: choice

## What does this print?

```python
x = [3, 1, 2]
y = sorted(x)
print(x)
```

- [x] `[3, 1, 2]`
- [ ] `[1, 2, 3]`
- [ ] `None`
- [ ] `[3, 2, 1]`

::: right
Right. `sorted` builds a new sorted list and leaves `x` as it was. `x.sort()` would sort `x` itself (and return `None`).
:::

::: misses
- [2] That's `y`. `sorted` returns a new list and doesn't touch `x`; `x.sort()` would.
- [3] `x` is still a list. `None` is what `x.sort()` returns, not what `x` becomes.
- [4] Nothing reverses the list, and `sorted` leaves `x` alone anyway.
:::
:::

::: explain
## After `y = x` with `x` a list, why does `x.append(5)` change `y` too?

::: model
`y = x` doesn't make a new list; it makes `y` a second name for the same list. There's only one list in memory, so changing it through either name changes what both names see. To get an independent list you have to copy it, with `y = x.copy()` or `y = x[:]`.
:::
:::

::: practice

::: check
kind: python
given: n = 6..15 int

## Set `evens` to the list of even numbers from 0 to `n` = {n} inclusive, using a comprehension.

```python starter
evens = []
print(evens)
```

```python solution
evens = [k for k in range(n + 1) if k % 2 == 0]
print(evens)
```

```python tests
assert evens == list(range(0, n + 1, 2)), "Keep the k in range(n + 1) with k % 2 == 0."
```
:::

::: check
kind: python
given: a = 1 | 2 | 3; b = 6 | 8

## The list `x = [5, 3, 9, 1, 7, 2, 8, 6]`. Set `part` to the slice from index `a` = {a} up to (not including) `b` = {b}, sorted.

```python starter
x = [5, 3, 9, 1, 7, 2, 8, 6]
part = x
print(part)
```

```python solution
x = [5, 3, 9, 1, 7, 2, 8, 6]
part = sorted(x[a:b])
print(part)
```

```python tests
assert part == sorted([5, 3, 9, 1, 7, 2, 8, 6][a:b]), "Slice with x[a:b], then sort the result."
```
:::

::: check
kind: python
given: s = 3 | 5 | 12

## Set `volts` to a list of floats from the string `"3.3,5,12,24"`, then set `n_big` to how many are greater than `s` = {s}.

```python starter
volts = []
n_big = 0
print(volts, n_big)
```

```python solution
volts = [float(p) for p in "3.3,5,12,24".split(",")]
n_big = len([v for v in volts if v > s])
print(volts, n_big)
```

```python tests
assert volts == [3.3, 5.0, 12.0, 24.0], "Split the string at commas and convert each piece with float."
assert n_big == sum(1 for v in [3.3, 5.0, 12.0, 24.0] if v > s), "Count those greater than s."
```
:::
:::
