Extended Zip Function with Fillvalue

  • Share this:

Code introduction


The function is similar to the built-in zip function, but it fills the shortest iterable with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Like zip() but the shortest iterable is extended by fillvalue.
    """
    from itertools import zip_longest

    def repeat(obj, n):
        return (obj,) * n

    iters = [iter(it) for it in iterables]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield result

# JSON representation                
              
Tags: