Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function combines multiple iterable objects into a new iterable object. If an iterable object is exhausted, it is filled with a specified value.


Technology Stack : itertools

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:
                result.append(fillvalue)
        yield result                
              
Tags: