zip stops at the shortest¶
Level: 201 · for Python programmers
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The bullets below are the questions the finished page has to answer.
One line: zip ends when any of its inputs ends and raises nothing, so pairing a hundred names with ninety-nine scores drops one row in silence; strict=True raises instead, itertools.zip_longest pads, and when an input is an iterator the dropped element has already been consumed from it.
What the finished page has to answer¶
- The default, measured on two lists of different lengths, and
dict(zip(keys, values))coming back one entry short with no error. zip(*args, strict=True), since 3.10, and theValueErrorit raises, named by type on the page.itertools.zip_longest(fillvalue=…), and why a fill value ofNoneis ambiguous whenNoneis data.- Which element is lost when one input is an iterator:
zippulls from its inputs left to right, so it has already taken the next item from the longer one before it learns that the shorter one ended, and that item is gone. Measured withlist(it)afterwards, the way An iterator is used up does. zip(*rows)as a transpose, and what a ragged row does to it.map(f, a, b)follows the same rule, andenumeratecannot be short because it makes its own counter.
See also¶
- An iterator is used up: why
zipitself lists only once zip↗ anditertools.zip_longest↗ in the Python docs, and PEP 618 ↗ forstrictzipandenumerate↗ in the Rust library, wherezipalso stops at the shorter and there is nostrict