Merging Iterables with Fillvalue in Python

  • Share this:

Code introduction


The function merges multiple iterable objects into an iterator. If an iterable object has been exhausted, fillvalue is used to fill in.


Technology Stack : Built-in libraries

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:
            yield result[0]
            break
        else:
            yield result