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

ParameterDescription
*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

Loop over two lists togetherTry it yourself
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
Build a dict, and unzipTry it yourself
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')
Different lengthsTry it yourself
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

VersionChange
Python 3.0Added
Python 3.10Added the strict parameter.