Iterating Over Iterables with FillValue

  • Share this:

Code introduction


This function returns an iterator that aggregates elements from each of the iterables, stopping when the shortest iterable is exhausted, and filling with fillvalue for the rest.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Returns an iterator that aggregates elements from each of the iterables. 
    The iterator stops when the shortest iterable is exhausted, filling with fillvalue for the rest.
    """
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield result