Python ยท Chapter 40 of 45
enumerate() & zip()
`enumerate(seq)` yields `(index, value)` pairs so you can loop with a counter.
`zip(a, b, ...)` yields tuples pairing items from multiple sequences.
enumerate(start=0)
The optional `start` argument changes where indexing begins (e.g. 1 for human-friendly numbering).
zip stops at shortest
If sequences differ in length, `zip` stops at the shorter one. Use `itertools.zip_longest` to keep all.
Example 1 (python)
for i, name in enumerate(["Ana","Ben","Cara"], start=1):
print(f"{i}. {name}")Output
1. Ana
2. Ben
3. CaraNumber a list starting from 1.
Example 2 (python)
names = ["Ana","Ben"]
scores = [90, 78]
for n, s in zip(names, scores):
print(n, s)Output
Ana 90
Ben 78Loop two lists in parallel.
Key points
- `enumerate` = index + value.
- `zip` = pair items across sequences.
- `enumerate(seq, start=1)` for 1-based indexing.
- Use `itertools.zip_longest` when lengths differ.
๐ก Note: You can 'unzip' with `zip(*pairs)` โ a neat trick to split a list of tuples into separate lists.
