Combining Iterables with FillValue

  • Share this:

Code introduction


This function combines multiple iterable objects into a single iterator. If one of the iterable objects is exhausted, fillvalue is used to fill in.


Technology Stack : itertools.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) == 1 and result[0] == fillvalue:
            break
        yield result