Merging Iterables with Fillvalue: The zip_longest Function

  • Share this:

Code introduction


The function merges multiple iterable objects into one iterator. If one iterable object finishes first, it fills with the specified fillvalue.


Technology Stack : itertools.zip_longest

Code Type : Iterator 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)
        if len(result) < len(args):
            break
        yield result