Iterating Over Multiple Iterables with Fillvalue

  • Share this:

Code introduction


This function creates an iterator that aggregates elements from each of the given iterables. It stops when the shortest iterable is exhausted, filling missing values with fillvalue.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    "Make an iterator that aggregates elements from each of the iterables."
    "It stops when the shortest iterable is exhausted, filling missing values with fillvalue."
    iterators = [iter(it) for it in iterables]
    while True:
        yield [next(it, fillvalue) for it in iterators]