You can download this code by clicking the button below.
This code is now available for download.
This function creates an iterator that aggregates elements from multiple iterable objects. If one of the iterable objects runs out of elements before the others, it continues to iterate using the fill value until the longest iterable object is exhausted.
Technology Stack : Built-in iterators, iterable objects, tuple
Code Type : Function
Code Difficulty : Intermediate
def zip_longest(*args, fillvalue=0):
"""Create an iterator that aggregates elements from each of the iterables.
The iterator returns elements from the iterables one by one until all of them are exhausted,
then it returns fillvalue until the longest iterable is exhausted.
Args:
*args: An arbitrary number of iterables.
fillvalue: The value to use if an iterable is exhausted before the others.
Returns:
An iterator that aggregates elements from the iterables.
"""
iters = [iter(iterable) for iterable in args]
longest = max(len(iters), key=len)
while True:
for i in range(longest):
try:
yield next(iters[i])
except StopIteration:
iters[i] = iter([fillvalue])