Implementing zip_longest in Python

  • Share this:

Code introduction


This function takes multiple iterable objects as input and returns an iterator that attempts to match the number of elements from each input. If an input runs out of elements, it uses the fillvalue to fill in.


Technology Stack : Iterator, generator

Code Type : Iterator

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    zip_longest_args = args
    num_inputs = len(zip_longest_args)
    iterator = iter(zip_longest_args)
    for first in next(iterator):
        yield [first]
        for rest in iterator:
            group = [next(iterator, fillvalue) for _ in range(num_inputs)]
            yield group