Python#s zip_longest Function Implementation

  • Share this:

Code introduction


This function uses the built-in zip_longest function to merge multiple iterable objects. If an object is not long enough, it is filled with fillvalue.


Technology Stack : Built-in function zip_longest, generator

Code Type : Generator function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    zip_longest_args = list(args)
    longest = max(len(arg) for arg in zip_longest_args)
    for i in range(longest):
        yield tuple(arg[i] for arg in zip_longest_args if i < len(arg))