Creating an Iterator for Zipping Longest Iterables with Fillvalue

  • Share this:

Code introduction


This function creates an iterator that returns the minimum number of elements from multiple iterable objects. If one of the iterable objects ends first, it fills in with the fillvalue.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    iters = [iter(arg) for arg in args]
    while True:
        result = []
        for i, it in enumerate(iters):
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)