Zip Longest Iterator for Aggregating Elements

  • Share this:

Code introduction


This function creates an iterator that aggregates elements from multiple iterable objects. When the shortest iterable is exhausted, it returns the fill value if provided, otherwise raises StopIteration.


Technology Stack : Built-in functions, iterators

Code Type : Function

Code Difficulty : Intermediate


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

    The iterator returns pairs of the form (i, val), where i is the index of the
    element from the iterable and val is the element obtained from the iterable.
    The iterator stops when the shortest iterable is exhausted, after which
    fillvalue is returned if provided, else raises StopIteration.

    Examples:
    >>> list(zip_longest('abc', 'x', fillvalue='-'))
    [('a', 'x'), ('b', '-'), ('c', '-')]
    >>> list(zip_longest('abc', 'x', 'xyz'))
    [('a', 'x'), ('b', 'y'), ('c', 'z')]
    """
    iterators = [iter(iterable) for iterable in iterables]
    while True:
        result = []
        for index, iterator in enumerate(iterators):
            try:
                result.append((index, next(iterator)))
            except StopIteration:
                iterators[index] = iter([fillvalue])
        yield result