Zip Longest Aggregation Function

  • Share this:

Code introduction


The function aggregates elements from multiple iterable objects and returns an iterator that yields tuples of index and value. If the iterables are of uneven length, missing values are filled with fillvalue.


Technology Stack : Built-in libraries

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, 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.

    If the iterables are of uneven length, missing values are filled-in
    with fillvalue. Default fillvalue is None.

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

    Yields:
        Tuples containing pairs of index and value from the iterables.
    """
    # Determine the longest iterator length
    iters = [iter(it) for it in args]
    longest = max(len(it) for it in iters, default=0)

    for i in range(longest):
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield i, tuple(result)