Zip Multiple Iterables with Fillvalue

  • Share this:

Code introduction


This function merges multiple iterables (such as lists or tuples) into one iterable. If the iterables are of uneven length, missing values are filled with `fillvalue`.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Zips multiple iterables (like lists or tuples) together into one iterable.
    If the iterables are of uneven length, missing values are filled with `fillvalue`.
    """
    from itertools import zip_longest
    from collections import deque

    def fill(iterable):
        for _ in range(len(args) - 1):
            iterable.append(fillvalue)

    max_length = max(len(arg) for arg in args)
    for _ in range(max_length - len(args[0])):
        fill(args[0])

    zipped = zip_longest(*args)
    return [list(item) for item in zipped]