Custom Zip Longest with Fillvalue

  • Share this:

Code introduction


This function implements similar functionality to `itertools.zip_longest`, filling shorter iterators with `fillvalue` when the lengths of input iterators differ.


Technology Stack : collections.deque, itertools.zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest
    from collections import deque
    
    def deque_iter(dq):
        for item in dq:
            if item is None:
                yield fillvalue
            else:
                yield item
    
    max_len = max(map(len, args))
    iterables = [deque(it) for it in args]
    zipped = deque_iter(zip_longest(*iterables, fillvalue=None))
    
    while len(zipped) < max_len:
        for i in range(len(iterables)):
            if len(iterables[i]) < max_len:
                iterables[i].append(None)
        zipped = deque_iter(zip_longest(*iterables, fillvalue=None))
    
    return list(zipped)