Python List Zip with Fill Value

  • Share this:

Code introduction


This function merges multiple lists into one, if the lists are of different lengths, it fills in the missing parts with a specified fill value.


Technology Stack : Built-in function zip, iterator, list comprehension

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    # This function will zip lists together and fill in missing values with a specified fillvalue.

    def _all_same_length(*args):
        return all(len(args[i]) == len(args[0]) for i in range(1, len(args)))

    def _zipper():
        iters = [iter(arg) for arg in args]
        for val in zip(*iters):
            for it in iters:
                yield next(it, fillvalue)

    if _all_same_length(*args):
        return list(zip(*args))
    else:
        return list(_zipper())