Python Implementation of itertools.zip_longest

  • Share this:

Code introduction


The function implements the functionality similar to `itertools.zip_longest`, which merges multiple iterable objects. If one of the iterable objects runs out, it uses `fillvalue` to fill.


Technology Stack : Built-in function

Code Type : Function

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:
                iters[i] = iter([fillvalue])
                result.append(fillvalue)
        yield tuple(result)