Zip Longest Function with Fillvalues

  • Share this:

Code introduction


The function is similar to zip(), but it fills the shorter sequences with fillvalues until all sequences have the same length.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Like zip() but the shortest input sequence is extended by fillvalues.
    """
    iters = [iter(arg) for arg in args]
    while True:
        result = []
        for iter_ in iters:
            try:
                result.append(next(iter_))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)