Zip Longest Function: Merging Iterables with Fillvalue

  • Share this:

Code introduction


The function accepts multiple iterable objects as arguments and returns an iterator that takes elements in sequence from each iterable. If an iterable is exhausted, it is filled with fillvalue.


Technology Stack : Iterators, Generators

Code Type : Function

Code Difficulty : Intermediate


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