Transforming and Combining Data · practice
Combine Sequences with zip()
enumerate() pairs each
For example, a quiz can store prompts and responses in matching
The previous lesson introduced enumerate(). Here it supplies each prompt together with its
This works, but the
Python’s zip() expresses that relationship directly:
zip produces pairs. The loop unpacks each pair into prompt and response.
Protect against silent truncation
zip stops when the shortest input ends:
list(zip(["A", "B"], [1]))
list(...) collects the pairs produced by zip into a list so you can inspect them. This produces only [("A", 1)]. The unmatched "B" is not reported.
Sometimes truncation is intentional. In a quiz engine, it usually means data was lost, so check the lengths before combining. As in Fundamentals I, raise stops the zip from silently discarding unmatched data:
if len(prompts) != len(responses):
raise ValueError("prompts and responses must have equal length")
Then use zip for the matching values.
What does this print?
print(list(zip(["A", "B", "C"], [1, 2])))Build attempt records
Combine equal-length prompt and response lists into a new list of
Task
Complete pair_attempts.
Raise
when the two have different lengths. over zip(prompt_list, response_list).Append
{"prompt": prompt, "response": response}for each pair.Return the new list.
Do not change either input list.