Zip Longest Function: Combining Iterables with Fill Value

  • Share this:

Code introduction


This function combines multiple iterable objects into an iterator. If one of the iterable objects is exhausted, it continues the iteration using a specified fill value.


Technology Stack : Built-in function zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    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 not any(result):
            break
        yield tuple(result)