Handling Different Length Iterables with FillValue

  • Share this:

Code introduction


The function implements a similar iteration functionality as zip, but can handle iterables of different lengths, filling the shorter ones with fillvalue.


Technology Stack : Built-in libraries

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    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) < len(args):
            break
        yield result