Zip Longest Iterator Function

  • Share this:

Code introduction


The function merges multiple iterators into a single iterator, using fillvalue to fill in if any iterator is exhausted.


Technology Stack : Built-in iterators

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    iters = [iter(arg) for arg in args]
    while True:
        result = []
        for i, it in enumerate(iters):
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)