zip()
zip() walks through two or more sequences at the same time and hands you their items paired up, one set per turn.
Used in 29 lessons of the course, from 01.01.
zip(a, b) takes two iterables and produces tuples: first (a[0], b[0]), then (a[1], b[1]), and so on.
You usually use it in a for with unpacking: for question, answer in zip(QUESTIONS, answers):. Each turn gives you one tuple, and Python splits it into two names. That way you don't have to keep an index by hand.
Two details matter. First, zip stops when the shortest iterable runs out; leftover items in the others are dropped without warning. Second, it returns an iterator, not a list: to see everything at once, wrap it with list(...).
In the course you meet it in lesson 01.01: it walks through the questions and the answers together, so each pair is handled as one unit.
Reach for it when: you have two lists that line up (like questions and answers) and you want to handle each pair together.
Examples
Common mistake
pairs = zip([1, 2], ["a", "b"]) print(pairs[0])
Why: `zip` returns an iterator, and an iterator doesn't support indexing like `pairs[0]`.
How to write it: Convert it first: pairs = list(zip(...)), then use pairs[0].
Common mistake
questions = ["a", "b", "c"]
answers = ["1", "2"]
for q, a in zip(questions, answers):
print(q, a)Why: One answer was missing and `zip` silently skipped question "c".
How to write it: Check that the lengths match, or use zip(a, b, strict=True) so it raises ValueError when they differ.
