You can download this code by clicking the button below.
This code is now available for download.
This function implements similar functionality to the zip function but can handle iterables of unequal length and can use fillvalue to fill in missing values.
Technology Stack : itertools
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*iterables, fillvalue=None):
"""
Zip the iterables together into a single iterable.
The returned iterable is an iterator of tuples, where the i-th tuple contains
the i-th element from each of the argument iterables. The iterator stops when the
shortest iterable is exhausted, but additional elements from the longer iterables
are filled in with fillvalue.
"""
iterators = [iter(it) for it in iterables]
for i, it in enumerate(iterators):
if not it:
iterators[i] = iter([fillvalue])
while True:
result = []
for it in iterators:
result.append(next(it, fillvalue))
yield tuple(result)