---
title: Iteration patterns
heading: enumerate, zip, sorted and the key that changes everything
eyebrow: A4 · Lesson 15 · Iteration patterns
xp: 40
---

::: hook
You have two lists, frequencies and gains from a sweep, and you want the frequency where the gain peaked. You could loop with an index, compare, remember the best index and look it up at the end. Or you could write one line. Python has a small set of tools for walking through data (enumerate, zip, sorted, min and max with a key, any and all) and knowing them makes analysis code short enough to read at a glance.
:::

::: predict
## `f = [100, 200, 400]` and `g = [0.9, 0.7, 0.4]`. What is `list(zip(f, g))`?

- [ ] `[100, 200, 400, 0.9, 0.7, 0.4]`
- [x] `[(100, 0.9), (200, 0.7), (400, 0.4)]`
- [ ] `[(100, 200, 400), (0.9, 0.7, 0.4)]`
- [ ] `[100.9, 200.7, 400.4]`

::: reveal
`[(100, 0.9), (200, 0.7), (400, 0.4)]`. `zip` pairs up items in the same position, like the teeth of a zipper. It's the natural way to walk through two matching lists together.
:::
:::

::: nameit
## Walking with an index: enumerate

```
for k, v in enumerate(readings):
    print(k, v)            # 0 3.31, 1 3.29, ...
```

Use `enumerate` instead of `for k in range(len(x))` whenever you need both the position and the value.

## Walking two lists together: zip

```
for freq, gain in zip(f, g):
    ...
pairs = list(zip(f, g))
```

`zip` stops at the shorter list. `dict(zip(names, values))` builds a dictionary from two lists.

## Sorting and picking by a key

`sorted`, `min` and `max` take a **key**: a function that says what to compare.

```
parts = [("R1", 4700), ("R2", 1000), ("R3", 22000)]
sorted(parts, key=lambda p: p[1])               # by value
max(zip(f, g), key=lambda p: p[1])              # the (freq, gain) with the biggest gain
min(values, key=lambda v: abs(v - target))      # the value nearest target
```

The key turns "find the best item by this measure" into one line, and returns the whole item, not just its score.

## Asking about all of them: any and all

```
all(v < 5.5 for v in readings)      # every reading under 5.5 V?
any(v < 0 for v in readings)        # any negative one?
```

They stop as soon as the answer is known.

## Running totals and differences

Many signal tasks look at neighbors:

```
diffs = [b - a for a, b in zip(x, x[1:])]          # differences
running = []
total = 0
for v in x:
    total += v
    running.append(total)                          # cumulative sum
```

`zip(x, x[1:])` pairs each item with the next one.
:::

::: example
## A sweep gives frequencies and gains. Find the frequency where the gain peaks.

::: solution
1. **Pair each frequency with its gain.** `zip` makes the pairs.
2. **Take the pair with the largest gain.** `max` with a key compares by the gain but hands back the whole pair.

```
f = [100, 200, 500, 1000, 2000, 5000]
g = [0.80, 0.95, 1.21, 1.10, 0.70, 0.30]
fpk, gpk = max(zip(f, g), key=lambda p: p[1])
print(fpk, gpk)          # 500 1.21
```

**Answer:** the gain peaks at 500 Hz, where it is 1.21.
:::
:::

::: example
## Find the indexes where a sampled signal crosses zero going up.

::: solution
1. **Compare each sample with the next.** Keep the index `k` where sample `k` is negative and sample `k + 1` isn't.

```
x = [-0.5, -0.1, 0.3, 0.8, 0.2, -0.4, -0.9, 0.1, 0.6]
ups = [k for k, (a, b) in enumerate(zip(x, x[1:])) if a < 0 <= b]
print(ups)               # [1, 6]
```

2. **Read the indexes.** Each crossing lies between sample `k` and `k + 1`.
3. **Where it's used.** Counting crossings like this is how a frequency counter measures a period in software.

**Answer:** the signal crosses zero going up at indexes 1 and 6, between samples 1 and 2 and between samples 6 and 7.
:::
:::

::: check
kind: python
given: k = 0..3 int

## For the sweep the starter picks, set `fpk` to the frequency where the gain `g` is largest.

```python starter
f = [100, 200, 500, 1000, 2000, 5000]
g = [[0.8, 0.95, 1.21, 1.1, 0.7, 0.3], [0.5, 0.6, 0.8, 1.4, 1.2, 0.9],
     [1.0, 1.3, 1.1, 0.9, 0.6, 0.4], [0.2, 0.4, 0.7, 0.9, 1.05, 1.2]][k]
fpk = None
print(fpk)
```

```python solution
f = [100, 200, 500, 1000, 2000, 5000]
g = [[0.8, 0.95, 1.21, 1.1, 0.7, 0.3], [0.5, 0.6, 0.8, 1.4, 1.2, 0.9],
     [1.0, 1.3, 1.1, 0.9, 0.6, 0.4], [0.2, 0.4, 0.7, 0.9, 1.05, 1.2]][k]
fpk = max(zip(f, g), key=lambda p: p[1])[0]
print(fpk)
```

```python tests
want = [500, 1000, 200, 5000][k]
assert fpk == want, f"fpk should be {want}: the frequency paired with the largest gain, not the largest frequency."
```

::: right
Right. Pair them with `zip`, compare by the gain, keep the frequency.
:::
:::

::: check
kind: python
given: target = 1500 | 3600 | 7000 | 50000

## Set `best` to the value in `values` (from the starter) nearest `target` = {target}, using `min` with a key.

```python starter
E6 = [1.0, 1.5, 2.2, 3.3, 4.7, 6.8]
values = [m * 10**d for d in range(2, 6) for m in E6]
best = min(values)
print(best)
```

```python solution
E6 = [1.0, 1.5, 2.2, 3.3, 4.7, 6.8]
values = [m * 10**d for d in range(2, 6) for m in E6]
best = min(values, key=lambda v: abs(v - target))
print(best)
```

```python tests
E6 = [1.0, 1.5, 2.2, 3.3, 4.7, 6.8]
vs = [m * 10**d for d in range(2, 6) for m in E6]
d = min(abs(v - target) for v in vs)
assert abs(abs(best - target) - d) < 1e-9, "Use min(values, key=lambda v: abs(v - target))."
```

::: right
Right. One line replaces the whole track-the-best loop from lesson 12.
:::
:::

::: check
kind: python
given: k = 0..3 int

## Set `ups` to the list of indexes `k` where the samples cross zero going up, between sample `k` and `k + 1` (sample `k` below 0, sample `k + 1` at or above 0).

```python starter
x = [[-0.5, -0.1, 0.3, 0.8, 0.2, -0.4, -0.9, 0.1, 0.6],
     [0.2, -0.3, 0.4, -0.1, -0.2, 0.5, 0.1, -0.6, 0.0],
     [-1.0, -0.5, 0.0, 0.5, 1.0, 0.5, 0.0, -0.5, -1.0, 0.2],
     [0.5, 0.3, -0.2, -0.7, -0.1, 0.4, 0.9, -0.3, 0.6]][k]
ups = []
print(ups)
```

```python solution
x = [[-0.5, -0.1, 0.3, 0.8, 0.2, -0.4, -0.9, 0.1, 0.6],
     [0.2, -0.3, 0.4, -0.1, -0.2, 0.5, 0.1, -0.6, 0.0],
     [-1.0, -0.5, 0.0, 0.5, 1.0, 0.5, 0.0, -0.5, -1.0, 0.2],
     [0.5, 0.3, -0.2, -0.7, -0.1, 0.4, 0.9, -0.3, 0.6]][k]
ups = [i for i, (a, b) in enumerate(zip(x, x[1:])) if a < 0 <= b]
print(ups)
```

```python tests
want = [[1, 6], [1, 4, 7], [1, 8], [4, 7]][k]
assert ups == want, f"ups should be {want}. Pair each sample with the next using zip(x, x[1:]), and keep the index where a < 0 <= b."
```

::: right
Right. `enumerate` gives the index and `zip(x, x[1:])` gives each neighbor pair.
:::
:::

::: check
kind: python
given: lim = 5.25 | 5.3 | 5.5

## Set `ok` to whether every reading is below `lim` = {lim} V, and `any_low` to whether any reading is below 4.75 V, using `all` and `any`.

```python starter
readings = [5.01, 4.98, 5.12, 5.27, 4.93, 5.05, 4.77, 5.18]
ok = None
any_low = None
print(ok, any_low)
```

```python solution
readings = [5.01, 4.98, 5.12, 5.27, 4.93, 5.05, 4.77, 5.18]
ok = all(v < lim for v in readings)
any_low = any(v < 4.75 for v in readings)
print(ok, any_low)
```

```python tests
r = [5.01, 4.98, 5.12, 5.27, 4.93, 5.05, 4.77, 5.18]
assert ok == all(v < lim for v in r), "ok should be all(v < lim for v in readings)."
assert any_low is False, "No reading is below 4.75 V, so any_low should be False."
```

::: right
Right. Both read like the question they answer.
:::
:::

::: check
kind: python
given: lo = 4.75 | 4.9; hi = 5.1 | 5.25; k = 1..5 int

## Using one list comprehension with `enumerate`, set `bad` to the list of `(index, value)` pairs for the readings outside `lo` = {lo} to `hi` = {hi} V (the edges count as in range). Then set `n_bad` to how many there are.

```python starter
import random
random.seed(k)
v = [round(5 + random.gauss(0, 0.15), 3) for _ in range(40)]
bad = [x for x in v if x < lo]
n_bad = 0
print(bad, n_bad)
```

```python solution
import random
random.seed(k)
v = [round(5 + random.gauss(0, 0.15), 3) for _ in range(40)]
bad = [(i, x) for i, x in enumerate(v) if x < lo or x > hi]
n_bad = len(bad)
print(bad, n_bad)
```

```python tests
import random
random.seed(k)
vs = [round(5 + random.gauss(0, 0.15), 3) for _ in range(40)]
want = [(i, x) for i, x in enumerate(vs) if not (lo <= x <= hi)]
assert bad == want, f"bad should list (index, value) for every reading outside {lo} to {hi}; there are {len(want)}."
assert n_bad == len(want), "n_bad is len(bad)."
```

::: right
Right. `enumerate` hands you each index with its value, and the `if` at the end of the comprehension keeps only the out-of-range ones.
:::
:::

::: check
kind: choice

## What is `[k * k for k in range(4) if k % 2 == 0]`?

- [x] `[0, 4]`
- [ ] `[0, 1, 4, 9]`
- [ ] `[4]`
- [ ] `[1, 9]`

::: right
Right. `range(4)` gives 0, 1, 2, 3; the `if` keeps the even ones, 0 and 2; and their squares are 0 and 4.
:::

::: misses
- [2] That ignores the `if`. Only even `k` are kept.
- [3] 0 is even too (0 % 2 is 0), and 0 × 0 is 0.
- [4] Those are the squares of the odd values. `k % 2 == 0` keeps the even ones.
:::
:::

::: explain
## Why is `max(zip(f, g), key=lambda p: p[1])` better than finding `max(g)` and then searching for it?

::: model
Finding `max(g)` gives only the peak gain, and you'd then need a second pass to find where it is, with a risk of mismatching if two gains are equal. Zipping the lists keeps each frequency attached to its gain, and `max` with a key compares by the gain but returns the whole pair. It does the job in one pass and can't get the two lists out of step.
:::
:::

::: practice

::: check
kind: python
given: k = 0..2 int

## Make `bom` a dictionary from the two lists `names` and `vals` with `dict(zip(...))`.

```python starter
names, vals = [(["R1", "R2"], [1000, 2200]), (["C1", "C2", "C3"], [1e-9, 1e-7, 1e-6]), (["L1"], [0.01])][k]
bom = {}
print(bom)
```

```python solution
names, vals = [(["R1", "R2"], [1000, 2200]), (["C1", "C2", "C3"], [1e-9, 1e-7, 1e-6]), (["L1"], [0.01])][k]
bom = dict(zip(names, vals))
print(bom)
```

```python tests
names, vals = [(["R1", "R2"], [1000, 2200]), (["C1", "C2", "C3"], [1e-9, 1e-7, 1e-6]), (["L1"], [0.01])][k]
assert bom == dict(zip(names, vals)), "Use dict(zip(names, vals))."
```
:::

::: check
kind: python
given: k = 0..2 int

## Set `by_value` to the parts sorted from smallest value to largest.

```python starter
parts = [[("R1", 4700), ("R2", 1000), ("R3", 22000)], [("C1", 1e-6), ("C2", 1e-9), ("C3", 4.7e-8)], [("L1", 0.1), ("L2", 0.001)]][k]
by_value = parts
print(by_value)
```

```python solution
parts = [[("R1", 4700), ("R2", 1000), ("R3", 22000)], [("C1", 1e-6), ("C2", 1e-9), ("C3", 4.7e-8)], [("L1", 0.1), ("L2", 0.001)]][k]
by_value = sorted(parts, key=lambda p: p[1])
print(by_value)
```

```python tests
parts = [[("R1", 4700), ("R2", 1000), ("R3", 22000)], [("C1", 1e-6), ("C2", 1e-9), ("C3", 4.7e-8)], [("L1", 0.1), ("L2", 0.001)]][k]
assert by_value == sorted(parts, key=lambda p: p[1]), "Sort with key=lambda p: p[1]."
```
:::

::: check
kind: python
given: k = 0..2 int

## Set `diffs` to the list of differences between neighboring samples, `x[k+1] - x[k]`.

```python starter
x = [[1, 4, 9, 16, 25], [10, 7, 5, 4], [0, 2, 1, 3, 2, 4]][k]
diffs = []
print(diffs)
```

```python solution
x = [[1, 4, 9, 16, 25], [10, 7, 5, 4], [0, 2, 1, 3, 2, 4]][k]
diffs = [b - a for a, b in zip(x, x[1:])]
print(diffs)
```

```python tests
x = [[1, 4, 9, 16, 25], [10, 7, 5, 4], [0, 2, 1, 3, 2, 4]][k]
assert diffs == [x[i + 1] - x[i] for i in range(len(x) - 1)], "Pair each sample with the next using zip(x, x[1:])."
```
:::
:::
