Zip Longest Function with Fillvalue

  • Share this:

Code introduction


This function is used to merge multiple iterable objects. If the iterable objects are of uneven length, fill in the missing values with fillvalue.


Technology Stack : itertools.zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    This function zips the input iterables (args) together, filling in missing values with the fillvalue
    if the iterables are of uneven length.
    """
    from itertools import zip_longest

    def _gen():
        iters = [iter(arg) for arg in args]
        while True:
            result = []
            for it in iters:
                try:
                    result.append(next(it))
                except StopIteration:
                    iters.remove(it)
            if not result:
                break
            yield tuple(result)

    return _gen()