Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

itertools.zip_longest

Pairs parallel iterable positions until the longest input ends.

Version: Python 3.14; repository image, production runtime not attested

Syntax

itertools.zip_longest(*iterables, fillvalue=None)

Pairs parallel iterable positions until the longest input ends.

Exhausted inputs supply the fill value. If any input is infinite the consumer must provide an external limit.

The first row pairs a with 7. The second source then ends, so the next row pairs b with the fill value. Iteration stops only when every input is exhausted; empty inputs emit no extra all-fill row. An infinite input requires an external bound such as islice.

import itertools as I
assert list(I.zip_longest("ab", [7], fillvalue="-")) == [("a", 7), ("b", "-")]
assert list(I.zip_longest([], [])) == []

Examples

import itertools as I
print(list(I.zip_longest("ab", [7], fillvalue="-")))
print(list(I.zip_longest([], [])))

Result

[('a', 7), ('b', '-')]
[]

The first row pairs a with 7. The second source then ends, so the next row pairs b with the fill value. Iteration stops only when every input is exhausted; empty inputs emit no extra all-fill row. An infinite input requires an external bound such as islice.

Sources