Creating an Iterator for Aggregating Iterables with Fillvalue

  • Share this:

Code introduction


The function creates an iterator that aggregates elements from the provided iterables. If the iterables are of uneven length, missing values are filled with fillvalue.


Technology Stack : Built-in library

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 pairs from the iterables. The returned pairs have the following form:
    (i1, i2, i3, ...), where i1 is the aggregate of the first item from each of the iterables, i2 is the aggregate of the second item
    from each of the iterables, and so on. If the iterables are of uneven length, missing values are filled-in with fillvalue.

    The iterator stops when the shortest iterable is exhausted.

    Args:
        *iterables: An arbitrary number of iterables.
        fillvalue: Value to use for missing values if the iterables are of uneven length.

    Returns:
        An iterator that aggregates elements from the provided iterables.

    """
    # Find the shortest iterable
    iters = [iter(i) for i in iterables]
    for i, it in enumerate(iters):
        if not it:
            iters[i] = iter([fillvalue])

    while True:
        # Aggregate the next item from each of the iterables
        result = [next(it, fillvalue) for it in iters]
        if all(x == fillvalue for x in result):
            break
        yield tuple(result)