Merging Iterables with Fillvalue

  • Share this:

Code introduction


The function is used to merge multiple iterable objects. If one of the iterable objects ends early, it uses fillvalue to fill in the remaining positions.


Technology Stack : Built-in functions

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 elements from the iterables. If the iterables
    are of uneven length, missing values are filled-in with fillvalue. The
    iterator stops when the shortest iterable is exhausted.
    """
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == 1:
            yield result[0]
        else:
            yield result