Merging Iterables with FillValue

  • Share this:

Code introduction


This function merges multiple iterable objects. If one of the iterable objects has been fully traversed, fillvalue is used to fill the remaining positions.


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 it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)                
              
Tags: