Dynamic List Zipping with Fill Values

  • Share this:

Code introduction


This function packages the lists of variable number of arguments together. If an element is missing in a list, it is filled with fillvalue.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest
    from collections import deque
    longest = max(len(list(arg)) for arg in args)
    for i in range(longest):
        yield tuple(arg[i] if i < len(arg) else fillvalue for arg in args)