Zip Longest Iterator for Aggregating Iterables

  • Share this:

Code introduction


This function is used to aggregate elements from multiple iterable objects into an iterator. If an iterable is exhausted, it is filled with a fillvalue.


Technology Stack : Iterators, generators

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    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
    corresponding iterable.
    """
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for i, it in enumerate(iters):
            try:
                result.append((i, next(it)))
            except StopIteration:
                iters[i] = iter([fillvalue])
                result.append((i, next(iters[i])))
        if len(result) == 0:
            break
        for i, (index, value) in enumerate(result):
            yield index, value