Combining Iterables with FillValue Using zip_longest

  • Share this:

Code introduction


The function is used to combine multiple iterable objects into an iterator. If one iterable object ends prematurely, fillvalue is used to fill the remaining positions.


Technology Stack : Built-in library

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) == 0:
            break
        yield tuple(result)