Iterating Multiple Iterables with FillValue

  • Share this:

Code introduction


This function merges multiple iterable objects into an iterator. If an iterable is exhausted first, it continues iteration with the specified fill value.


Technology Stack : zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    zip_longest_args = [iter(arg) for arg in args]
    while True:
        result = []
        for i, it in enumerate(zip_longest_args):
            try:
                result.append(next(it))
            except StopIteration:
                zip_longest_args[i] = iter([fillvalue])
                result.append(next(it))
        yield result                
              
Tags: