Mimicking itertools.zip_longest with Fillvalue Padding

  • Share this:

Code introduction


This function mimics the `itertools.zip_longest` function to zip equal length sequences together, padding the shorter sequences with a `fillvalue` if they are of unequal length.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    This function mimics the `itertools.zip_longest` function to zip equal length sequences together
    so that the shorter sequences are padded with a fillvalue.
    """
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for iter_ in iters:
            try:
                result.append(next(iter_))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)

# JSON representation of the function                
              
Tags: