Creating an Aggregating Iterator with FillValue

  • Share this:

Code introduction


This function creates an iterator that aggregates elements from the given iterable objects. If one of the iterable objects is exhausted first, the `fillvalue` is used to fill in the missing values.


Technology Stack : Iterator

Code Type : Iterator

Code Difficulty : Intermediate


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

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

    Examples:
    >>> list(zip_longest([1, 2, 3], [4, 5], [6], fillvalue=0))
    [(1, 4, 6), (2, 5, None), (3, None, None)]
    >>> list(zip_longest([1, 2, 3], [4, 5], [6], fillvalue='x'))
    [(1, 4, 6), (2, 5, 'x'), (3, None, 'x')]

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

    Returns:
        An iterator that aggregates elements from each of the iterables.
    """
    iterators = [iter(i) for i in iterables]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == len(iterables):
            break
        yield result                
              
Tags: