Sub topic 3
Using `enumerate` and `zip` Together
Assume you know Python for loops, lists, tuples, dictionaries, and function calls. This chapter focuses on combining enumerate and zip, reshaping paired data, and avoiding exhausted iterators.
Using `enumerate` and `zip` Together
zip pairs items from multiple iterables. enumerate adds an index to each result. Together, they let you number related records without manual counters.
names = ["Ada", "Grace", "Linus"]
scores = [95, 88, 91]
for number, (name, score) in enumerate(
zip(names, scores),
start=1,
):
print(f"{number}. {name}: {score}")The loop receives values like (1, ("Ada", 95)). The loop header unpacks both layers:
numberreceives the index.(name, score)receives the pair produced byzip.
Building Dictionaries and Unzipping with `zip`
Use dict(zip(keys, values)) when two sequences represent corresponding keys and values.
fields = ["name", "language", "year"]
values = ["Python", "programming", 1991]
record = dict(zip(fields, values))
print(record)This prints {'name': 'Python', 'language': 'programming', 'year': 1991}.
You can reverse paired data with the unpacking operator *. The result is a tuple for each column.
pairs = [(1, "x"), (2, "y"), (3, "z")]
numbers, letters = zip(*pairs)
print(numbers)
print(letters)Iterators Are Used Up
In Python, zip and enumerate return iterators. An iterator produces values lazily and is consumed as you loop over it. It cannot normally be restarted.
pairs = zip([1, 2, 3], ["a", "b", "c"])
print(list(pairs))
print(list(pairs))The first call prints all pairs. The second prints [] because no values remain. Create a new iterator, or save the results in a list when you need to reuse them.
Exercise
How can you print numbered names and scores using one loop?
Show answer
Use enumerate(zip(names, scores), start=1) and unpack each item as number, (name, score).