Python zip_longest Function Explained

  • Share this:

Code introduction


This function combines multiple iterable objects (such as lists, tuples, etc.) into a list of tuples. If the iterables are of unequal length, missing values are filled in with fillvalue. If no fillvalue is provided, the default is None.


Technology Stack : itertools.zip_longest, islice, chain, repeat, tee

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Zip equal length sequences together into a list of tuples. If the sequences are of uneven length,
    missing values are filled-in with fillvalue. Default fillvalue is None.
    """
    from itertools import zip_longest as zip_longest_from_itertools
    from itertools import zip_longest
    from itertools import islice
    from itertools import chain
    from itertools import repeat
    from itertools import tee

    def iterables_zip_longest(fillvalue):
        for iterable in iterables:
            if len(iterable) > 0:
                for value in iterable:
                    yield value
            else:
                yield fillvalue

    return list(zip_longest_from_itertools(iterables_zip_longest(fillvalue), fillvalue))