Extended Zip Function with Fillvalue

  • Share this:

Code introduction


The function iterates over multiple iterable objects. If one of the iterable objects is exhausted, it fills the remaining positions with the fillvalue.


Technology Stack : zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    iters = [iter(arg) for arg 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
    return tuple(result)                
              
Tags: