A415 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

A4 · Lesson 15 · Iteration patterns

enumerate, zip, sorted and the key that changes everything

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

Name it

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.

Worked example

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

Show the 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.

Worked example

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

Show the 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]
  1. Read the indexes. Each crossing lies between sample k and k + 1.
  2. 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

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

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Set ok to whether every reading is below lim = 5.3 V, and any_low to whether any reading is below 4.75 V, using all and any.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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

Explain why

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

Practice

Keep practicing

8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.