Zip Longest Function: Merging Iterables with Fillvalue

  • Share this:

Code introduction


The function is used to merge multiple iterable objects into a single iterator. If an iterable object is exhausted, fillvalue is used to fill it.


Technology Stack : Iterator, generator

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:
                iters[i] = iter([fillvalue])
                result.append(fillvalue)
        yield tuple(result)