Combining Iterables with FillValue Using zip_longest

  • Share this:

Code introduction


This function is used to combine multiple iterable objects into a new iterator. If an iterable is exhausted, it is filled with fillvalue.


Technology Stack : itertools.zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == len(args):
            yield result
        else:
            break