Sub topic 2
Counting and Pairing Data with `enumerate` and `zip`
Assume you know basic for loops, lists, tuples, dictionaries, and function calls. This chapter covers numbered loops, parallel iteration, and mismatched input lengths.
Counting from 1 with `enumerate`
enumerate produces an index and a value for each item. Its start argument sets the first index. Python normally counts from zero, but start=1 is useful for human-facing numbers.
tasks = ["write", "test", "ship"]
for number, task in enumerate(tasks, start=1):
print(f"{number}. {task}")Output:
1. write
2. test
3. shipThe loop uses tuple unpacking: each result from enumerate is an (index, value) pair.
Looping over sequences in parallel
zip pairs items at the same position from two or more iterables. An iterable is an object that can provide items one at a time, such as a list.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for name, score in zip(names, scores):
print(f"{name}: {score}")The first name pairs with the first score, the second name with the second score, and so on.
You can combine enumerate and zip when you need both a row number and multiple values:
for row, (name, score) in enumerate(zip(names, scores), start=1):
print(f"{row}. {name}: {score}")The parentheses around (name, score) unpack the tuple created by zip.
When lengths differ
By default, zip stops when the shortest input ends.
| Method | Behavior with unequal lengths |
|---|---|
| `zip(a, b)` | Stops at the shortest input |
| `zip(a, b, strict=True)` | Raises `ValueError` |
| `zip_longest(a, b)` | Continues and fills missing values |
Use strict=True when different lengths indicate a data error. Use zip_longest when missing values are expected.
from itertools import zip_longest
left = [1, 2, 3]
right = ["a", "b"]
print(list(zip(left, right)))
print(list(zip_longest(left, right, fillvalue="-")))
try:
list(zip(left, right, strict=True))
except ValueError:
print("The inputs have different lengths")Exercise
Which expression should you use to number items from 1 while looping over it?
Show answer
enumerate(items, start=1).