Python Reference ยท Built-in Functions
Python zip() function
Reference for Python zip(): pair items from several iterables, strict mode (3.10), uneven lengths, itertools.zip_longest, unzipping and building dicts.
The built-in zip() walks several iterables in parallel and yields tuples, each holding one item from every iterable: the first items together, then the second items, and so on. It returns a lazy iterator, so wrap it in list() or loop over it to see the pairs.
By default zip() stops at the shortest input and silently drops the rest. Since Python 3.10 you can pass strict=True to raise an error when lengths differ.
list(zip([1, 2, 3], "abc")) # [(1, 'a'), (2, 'b'), (3, 'c')]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
zip(*iterables, strict=False)
| Name | Description |
|---|---|
*iterables |
Zero or more iterables to combine. |
strict |
Keyword-only (3.10+). If True, raise ValueError when the iterables have different lengths. |
Return value: a zip iterator yielding tuples of length equal to the number of iterables.
Raises: ValueError in strict mode when lengths differ; TypeError if an argument is not iterable.
Usage notes
- Shortest wins.
zip([1, 2, 3], [1])yields one pair. The bug is easy to miss; usestrict=Truewhen equal lengths are an invariant, oritertools.zip_longest()to pad. - One-shot. The result is an iterator; once consumed it is empty. Convert to a list to reuse it.
- Consumption order.
zip()takes an item from each iterable in turn; with strict mode off, an item pulled from an earlier iterator just before a later one ends is lost. - Unzipping.
zip(*pairs)transposes: it turns a list of tuples into separate sequences, and it also transposes a matrix. The results are tuples. - Building dicts.
dict(zip(keys, values))is the standard way to combine two lists into a mapping. - Parallel loops. Prefer
for a, b in zip(x, y)over indexing withrange(len(x)). - Without arguments the result is empty; with one argument, one-element tuples.
- Sorting together. Zip, sort, then unzip to reorder two lists by one of them.
- In Python 2
zip()built a list; in Python 3 it is lazy.
Related
enumerate(),map(),filter(),sorted(),dict()- Lessons: For loops, Unpacking, Itertools and functools