Iterative Zip with FillValue Support

  • Share this:

Code introduction


This function takes any number of iterable objects as arguments and returns an iterator that yields tuples with the longest input length, filling shorter inputs with fillvalue.


Technology Stack : itertools, collections, operator

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import deque
    from operator import itemgetter

    def fill_deques(deques):
        max_length = max(len(d) for d in deques)
        for d in deques:
            while len(d) < max_length:
                d.append(fillvalue)

    def get_max_length(deques):
        return max(len(d) for d in deques)

    deques = [deque(iter(arg)) for arg in args]
    fill_deques(deques)

    while True:
        try:
            result = [d.popleft() for d in deques]
        except IndexError:
            break

        yield result