Iterative Zip with Fillvalue

  • Share this:

Code introduction


The function merges multiple iterable objects into a single iterator. If an element in one of the iterable objects is exhausted, it is filled with fillvalue.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    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)
                iters[i] = iter([fillvalue])
        yield result