Merging Iterables with Fillvalue

  • Share this:

Code introduction


This function merges multiple iterable objects. If an iterable object is exhausted, fillvalue is used to fill the remaining positions.


Technology Stack : Built-in function

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    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) == 1 and result[0] is fillvalue:
            break
        yield tuple(result)