Python Implementation of zip_longest from itertools

  • Share this:

Code introduction


This function uses the `zip_longest` function from the `itertools` module to merge multiple iterable objects into an iterator. If an iterable object does not have enough elements, it is filled with `fillvalue`.


Technology Stack : itertools, zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest

    def zip_longest_inner(*args, fillvalue=0):
        for i in range(max(len(a) for a in args)):
            yield tuple(a[i] if i < len(a) else fillvalue for a in args)

    return zip_longest_inner(*args, fillvalue=fillvalue)