Merging Iterables with Fillvalue

  • Share this:

Code introduction


The function merges multiple iterable objects into an iterator. If an iterable object is exhausted, it uses fillvalue to fill in.


Technology Stack : Built-in functions, iterators

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    iters = [iter(lst) for lst in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)