Merging Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


This function uses `itertools.zip_longest` to merge multiple iterable objects. If one of the iterable objects ends prematurely, it fills the remaining positions with `fillvalue`.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


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

    def create_iterables(args):
        for arg in args:
            if isinstance(arg, list):
                yield arg
            else:
                yield [arg]

    iterators = create_iterables(args)
    return zip_longest(*iterators, fillvalue=fillvalue)                
              
Tags: