Combining Iterables with Fill Value

  • Share this:

Code introduction


This function takes multiple iterable objects as arguments and combines them into a new iterable, filling the shorter sequences with a specified fill value if necessary.


Technology Stack : itertools (built-in library)

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Group elements of several iterable objects and fill with fillvalue if the shorter iterable is exhausted.
    """
    from itertools import zip_longest

    def iterables_to_zip(*iterables):
        for iterable in iterables:
            for element in iterable:
                yield element

    return list(iterables_to_zip(*args, fillvalue=fillvalue))