Merging Iterables with Fillvalue in Zip Longest

  • Share this:

Code introduction


The function merges multiple iterable objects into one iterator, if one of the iterable objects is exhausted, it fills the remaining positions with fillvalue.


Technology Stack : Iterator

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    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)
        if len(result) == len(args):
            break
    return result                
              
Tags: