Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function combines multiple iterable objects. If some iterable objects are shorter than others, it fills the remaining positions with a specified fill value.


Technology Stack : Iterators, Generators

Code Type : Function

Code Difficulty : Intermediate


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