⚡ Comprehensions & Iteration, lesson 3 of 5
enumerate() and zip()
Loop with an index, or walk through several lists side by side.
9 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
Need the position and the item? Instead of
range(len(items)), use enumerate. It hands
you (index, item) pairs. Pass start=1 to count
from 1.
Numbered to-do list
Remove start=1 and see where the numbering begins.
Find the spikes
The index tells you where each spike happened.
What does this print?
zip walks through several sequences side by
side, giving you a tuple with one item from each.
dict(zip(keys, values)) is a quick way to pair two
lists into a dictionary.
Zip names and scores
Add a third list, ages, and zip all three.
Shortest wins
Where did Wednesday go? Add strict=True inside zip(...) to get an error instead.
Day-to-day changes
Zipping a list with itself shifted by one gives
neighbouring pairs. :+ always shows the sign.
What does this print?
Invoice builder
The three lists line up by position.
totals: a dict mapping each item toqty * price(usezip).grand_total: the sum of all the totals.numbered:["1. pen", "2. pad", "3. ink"](useenumerate).