Combining Iterables with FillValue Using zip_longest

  • Share this:

Code introduction


This function uses the zip_longest function from the itertools module to combine multiple iterable objects. If the iterable objects are of unequal length, it fills with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


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

    def iterables_to_tuple(iterable):
        for i in iterable:
            if hasattr(i, '__iter__') and not isinstance(i, str):
                yield tuple(i)
            else:
                yield (i,)

    iters = map(iterables_to_tuple, args)
    zipped = zip_longest(*iters, fillvalue=fillvalue)
    return zipped                
              
Tags: