Combining Iterables with Fillvalue in Python

  • Share this:

Code introduction


The function is used to combine iterable objects into a new iterator. If an iterable object is traversed out, fillvalue is used to fill the remaining positions.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    iters = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == 1 and result[0] is fillvalue:
            break
        yield result