Iterating Aggregated Elements with Fillvalue

  • Share this:

Code introduction


This function returns an iterator that aggregates elements from each of the iterables. The iterator returns pairs of elements from the iterables. When the shortest iterable is exhausted, missing values are filled-in with fillvalue.


Technology Stack : Iterator, iteration

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Return an iterator that aggregates elements from each of the iterables. 
    The iterator returns pairs of elements from the iterables. 
    When the shortest iterable is exhausted, missing values are filled-in with fillvalue.
    """
    iterators = [iter(iterable) for iterable in args]
    while True:
        yield tuple(next(it, fillvalue) for it in iterators)