Combining Iterables with Fillvalue

  • Share this:

Code introduction


The function combines multiple iterable objects. If an iterable object is exhausted, it fills in the missing parts with the fillvalue.


Technology Stack : Built-in functions

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    iters = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == len(args):
            return result
        else:
            break