Iterating Over Variable Length Iterables with FillValue

  • Share this:

Code introduction


This function accepts any number of iterable objects as arguments and returns an iterator that fills in the missing values with fillvalue when the elements are insufficient.


Technology Stack : Built-in function zip_longest

Code Type : Function

Code Difficulty : Intermediate


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