Generator for Zipping Longest Iterables

  • Share this:

Code introduction


This function creates a generator that combines multiple iterable objects into one. If an iterable is exhausted, it fills with the fillvalue.


Technology Stack : Built-in functions zip, next, StopIteration, generator

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for iter_ in iters:
            try:
                result.append(next(iter_))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == 1 and result[0] == fillvalue:
            return
        yield tuple(result)