Python Function for Zip Longest with Fillvalue

  • Share this:

Code introduction


The function accepts any number of iterable objects as arguments and uses `itertools.zip_longest` to merge them. If an element is missing in one of the iterables, it is filled with `fillvalue`. Finally, it returns the result as a list.


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

    def iterables_to_deques(iterables):
        return [deque(iterable) for iterable in iterables]

    def unfill_deques(deques):
        return [deque[i] for i, deque in enumerate(deques) if i < len(deque)]

    zipped = zip_longest(*iterables_to_deques(args))
    return unfill_deques(zipped)