Iterators and generators
Enumerate, zip, and lazy processing
Pair positions and related streams carefully.
Lesson 57 of 63
Reading: about 2 min
Lesson + practice: about 15 min
Difficulty: Intermediate
On this page5 sections
enumerate pairs each value with an index. zip pairs values from multiple iterables and stops at the shortest input by default.
Worked example
subjects = ["Python", "SQL"]
minutes = [20, 30]
for index, (subject, value) in enumerate(zip(subjects, minutes), start=1):
print(index, subject, value)1 Python 20 2 SQL 30
Why this works
zip creates pairs as the loop requests them. enumerate numbers those pairs starting at 1. With strict=True, consuming mismatched inputs raises ValueError instead of discarding an unmatched value.
Another case
print(list(zip([1, 2], ["a"], strict=True)))Traceback (most recent call last):
File "zip_strict.py", line 1, in <module>
print(list(zip([1, 2], ["a"], strict=True)))
ValueError: zip() argument 2 is shorter than argument 1Your terminal may show the full path to the file instead of just its name. Python 3.11 and newer also add ^ or ~ marker lines under the part of the line that failed, and recent versions colour the output. The last line, with the error type and message, is the same.
Practice
Predict list(zip([1, 2], ["a"])) and explain the missing second pair.
Check the practice result
Reveal answer
It is [(1, "a")]; zip stops when the shorter input ends.
Try another case
What does list(enumerate(["a", "b"])) produce?
Check your answer
Reveal answer
[(0, "a"), (1, "b")]. enumerate starts at 0 unless you pass start=1.
Your progress
Reveal the check answer or reach the end to complete this lesson.