Python 3 reference · Built-in Functions
Python zip() Function
Iterate over several iterables in parallel, producing tuples of their items. Stops at the shortest unless strict=True.
Python 3 Since 3.0
Syntax
zip(*iterables, strict=False)
Parameters
| Parameter | Description |
|---|---|
*iterables |
Two or more iterables to combine. |
strict optional |
Raise ValueError if the iterables have different lengths. Default: False |
Return value
An iterator of tuples.
Examples
names = ["Ada", "Linus", "Grace"]
ages = [36, 28, 85]
for name, age in zip(names, ages):
print(name, age)
Output
Ada 36 Linus 28 Grace 85
keys = ["a", "b", "c"]
values = [1, 2, 3]
print(dict(zip(keys, values)))
pairs = [(1, "x"), (2, "y")]
numbers, letters = zip(*pairs) # "unzip"
print(numbers, letters)
Output
{'a': 1, 'b': 2, 'c': 3}
(1, 2) ('x', 'y')print(list(zip([1, 2, 3], ["a", "b"]))) # silently drops 3
try:
list(zip([1, 2, 3], ["a", "b"], strict=True))
except ValueError as e:
print("ValueError:", e)
Output
[(1, 'a'), (2, 'b')] ValueError: zip() argument 2 is shorter than argument 1
Common mistakes
zip() silently stops at the shortest input, which can hide bugs. Pass strict=True (Python 3.10+) when the
inputs must have the same length, or use itertools.zip_longest() to pad the shorter ones.
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.10 | Added the strict parameter. |
Related
enumerate()· Loop over an iterable and get each item together with its index, as (index, item) pairs. The start number is configurable.map()· Apply a function to every item of one or more iterables and return a lazy iterator of the results.dict()· Create a dictionary: a mapping of keys to values. Build it from keyword arguments, pairs or another mapping.- Python For Loops · tutorial
- Python Dictionaries · tutorial