Combining Iterables with FillValue

  • Share this:

Code introduction


This function combines multiple iterable objects into a new iterator. If an iterable object is exhausted, it uses fillvalue to fill.


Technology Stack : Built-in functions: next(), yield

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 not result:
            break
        yield result