You can download this code by clicking the button below.
This code is now available for download.
This function implements functionality similar to the built-in zip function, but it continues to generate tuples filled with a fill value until all input iterators are exhausted when the shortest one is.
Technology Stack : Iterators
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=None):
"""
Like zip(), returns an iterator that aggregates elements from each of the iterables.
The iterator stops when the shortest iterable is exhausted, unlike zip(), which
stops when the longest iterable is exhausted.
:param args: An arbitrary number of iterables.
:param fillvalue: Value to use for missing values from shorter iterables.
:return: An iterator.
"""
iters = [iter(iterable) for iterable in args]
while True:
result = []
for iter_ in iters:
try:
result.append(next(iter_))
except StopIteration:
result.append(fillvalue)
yield tuple(result)