Combining Iterables with Fillvalue in Python

  • Share this:

Code introduction


This function combines iterable objects into a list of tuples. If the iterators are exhausted, fillvalue is used to fill in.


Technology Stack : itertools, iterators

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for iter_ in iters:
            try:
                result.append(next(iter_))
            except StopIteration:
                result.append(fillvalue)
        if not result:
            break
        yield result