Parallel iteration
Associate records with corresponding labels, IDs, or configuration values while iterating in lockstep.
Python · Function
zip() iterates over multiple iterables in parallel and yields tuples of corresponding elements. It is lazy and can optionally require equal input lengths with strict=True.
Call zip with one or more iterables to obtain a lazy iterator whose tuples contain corresponding elements from each input. Iteration advances the inputs in parallel; by default, it ends when the shortest input ends, while strict=True detects length mismatches.
zip(*iterables, strict=False)| Name | Type | Description |
|---|---|---|
*iterables | iterable | The iterables whose corresponding elements should be grouped into output tuples. |
strict | bool | If true, require all iterables to be exhausted together; otherwise a length mismatch raises an exception. |
A lazy iterator of tuples; each tuple contains one element from each input iterable.
names = ["Ada", "Linus", "Guido"]
roles = ["engineer", "designer", "author"]
for name, role in zip(names, roles, strict=True):
print(f"{name}: {role}")Pairs corresponding elements and raises an error if the inputs have different lengths.
Associate records with corresponding labels, IDs, or configuration values while iterating in lockstep.
Convert row-oriented sequences into column-oriented groups or reconstruct rows from columns.
Fail fast when parallel inputs must contain the same number of elements.
zip() returns a lazy iterator of tuples. The i-th tuple contains the i-th element from every argument iterable, and iteration stops when the shortest input is exhausted by default.
Follow-up: What changes with strict=True? It validates that the iterables finish together and raises an exception when their lengths differ.
strict=True asks zip() to verify that all input iterables have equal lengths. A mismatch raises an exception instead of silently discarding unmatched trailing elements.
Follow-up: When is this preferable? Use it when parallel data represents corresponding records and truncation would hide a bug.
zip() is lazy, so it does not process elements until the result is iterated, such as in a for loop or after conversion to list. This allows parallel processing without immediately materializing all tuples.
Follow-up: How can you materialize the result? Pass the iterator to list(), which consumes it and stores the resulting tuples.
iter()list()tuple()map()