Python 3.0+itertoolsfunction
itertools.zip_longest
itertools
Like zip(), but continues to the longest iterable, padding with fillvalue.
Syntax
itertools.zip_longest(*iterables, fillvalue=None)
It is lazy — it returns an iterator and produces tuples on demand. The catch: fillvalue is a single shared value for every short iterable, and its default None easily collides with a genuine None in your data, so you cannot tell padding apart from a real value. Its opposite is zip(..., strict=True) from 3.10, which instead raises when the lengths differ.
Examples
import itertools
print(list(itertools.zip_longest([1, 2], ['a'], fillvalue='?'))) # → [(1, 'a'), (2, '?')]
print(list(itertools.zip_longest([1, 2], ['a']))) # → [(1, 'a'), (2, None)]
print(list(zip([1, 2], ['a']))) # → [(1, 'a')]
print([sum(p) for p in itertools.zip_longest([1, 2, 3], [10, 20], fillvalue=0)]) # → [11, 22, 3]
print(list(itertools.zip_longest('ab', '1', '', fillvalue='-'))) # → [('a', '1', '-'), ('b', '-', '-')]
See also
Open in the full glossarydocs.python.orgReport an inaccuracy