0%

Transforming and Combining Data · practice

Combine Sequences with zip()

enumerate() pairs each with a position created by Python. Sometimes the values we need already exist in two separate sequences.

For example, a quiz can store prompts and responses in matching :

Try it

The previous lesson introduced enumerate(). Here it supplies each prompt together with its . That index then reads the response at the matching position.

This works, but the still manages a number and uses it to look inside the second list. The real relationship is simpler: the first prompt belongs with the first response, the second prompt with the second response, and so on.

Python’s zip() expresses that relationship directly:

Try it

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 when its input breaks a rule. Here it prevents 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 . Reject mismatched lengths rather than silently dropping data.

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.