Iterative Zip with Fillvalue for Variable Length Iterables

  • Share this:

Code introduction


The function merges multiple iterable objects into a single iterator. If the iterables are of different lengths, it fills the shorter ones with the fillvalue.


Technology Stack : Iterator, generator

Code Type : Function

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:
                iters[i] = iter([fillvalue])
                result.append(fillvalue)
        yield result