Creating an Aggregated Iterator for Multiple Iterables

  • Share this:

Code introduction


The function aggregates elements from multiple iterable objects and returns an iterator that takes elements from each iterable. If one of the iterables is exhausted while another still has remaining elements, the fillvalue can be used to fill in the missing values.


Technology Stack : Built-in libraries

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """Create an iterator that aggregates elements from each of the iterables.

    Returns a new iterator object that returns pairs of elements from the
    iterables. The returned iterator is lazy, so the elements are only
    computed on demand.

    The iterator stops when the shortest iterable is exhausted, unless the
    *fillvalue* is specified, in which case missing values are filled in from
    *fillvalue*.

    Args:
        *iterables: An arbitrary number of iterables.
        fillvalue: The value to use for missing values in the shorter iterables.

    Returns:
        An iterator that aggregates elements from each of the iterables.

    """
    iterators = [iter(it) for it in iterables]
    while True:
        yield [next(it, fillvalue) for it in iterators]