Python zip_longest Function Explanation

  • Share this:

Code introduction


The function takes multiple iterable objects as arguments and returns an iterator that gets elements from each iterable. If an iterable is exhausted, it is filled with fillvalue.


Technology Stack : Built-in function zip_longest

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)
        yield tuple(result)