Combining Iterables with Fillvalue in zip_longest

  • Share this:

Code introduction


The zip_longest function is used to combine multiple iterable objects into one iterator, filling the missing values with a specified fillvalue if an iterable ends prematurely.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    # zip_longest is used to combine several iterables into one, filling missing values with a specified fillvalue
    from itertools import zip_longest
    from collections import deque

    iters = [deque(iterable) for iterable in iterables]
    while iters:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                it.append(fillvalue)
        yield tuple(result)