Creating an Aggregating Iterator for Variable-Length Iterables

  • Share this:

Code introduction


The function creates an iterator that aggregates elements from each of the iterables. The iterator returns elements from the first iterable until it is exhausted, then moves to the next iterable, until all of the iterables are exhausted.


Technology Stack : Iterator, generator, tuple

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Returns an iterator that aggregates elements from each of the iterables.
    The iterator returns elements from the first iterable until it is exhausted,
    then moves to the next iterable, until all of the iterables are exhausted.
    """
    iterators = [iter(it) for it in iterables]
    for i in iterables:
        next(i, None)
    while True:
        result = []
        for it in iterators:
            result.append(next(it, fillvalue))
        if None in result:
            break
        yield tuple(result)