Aggregating Iterators with FillValue Support

  • Share this:

Code introduction


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


Technology Stack : Built-in libraries

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Return an iterator that aggregates elements from each of the iterables.
    The iterator stops when the shortest iterable is exhausted, filling
    missing values with fillvalue until the longest iterable is exhausted.
    """
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield result