Python Implementation of itertools.zip_longest with Fillvalue

  • Share this:

Code introduction


This function implements a similar functionality to `itertools.zip_longest`. When the input iterators have different lengths, it uses `fillvalue` to fill in the shorter iterators.


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 fill(deq):
        while len(deq) < max(len(x) for x in args):
            deq.append(fillvalue)

    deques = [deque(list(x)) for x in args]
    fill(deques)
    while True:
        yield [d[0] for d in deques if d]
        for deq in deques:
            if deq:
                deq.popleft()
                fill(deq)