Zip Longest Iterator for Aggregating Elements from Multiple Iterables

  • Share this:

Code introduction


This function creates an iterator that aggregates elements from multiple iterable objects. If an iterable is exhausted before the others, it can be filled with a specified fillvalue.


Technology Stack : Built-in functions

Code Type : Function

Code Difficulty : Intermediate


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

    Returns a new iterator object that returns elements from the first iterable until
    it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.

    The iterator stops when the shortest iterable is exhausted, unless the *fillvalue* is
    specified. In that case, missing values in the shorter iterables are filled in with
    *fillvalue*.

    :param *iterables: An arbitrary number of iterable objects.
    :param fillvalue: The value to use for missing values in the iterables (default: None).
    :return: An iterator that aggregates elements from the provided iterables.
    """
    iterators = [iter(i) for i in iterables]
    while True:
        yield [next(i, fillvalue) for i in iterators]