Creating a Zip Longest Generator in Python

  • Share this:

Code introduction


This function uses the `itertools` and `collections` modules to create a generator that combines iterators into tuples. If the iterators are of different lengths, it fills the shorter ones with `fillvalue`.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    from itertools import zip_longest
    from collections import deque

    def fill(deq):
        for i in range(len(deq)):
            deq[i].append(fillvalue)

    # Ensure all iterables are of the same length
    max_length = max(len(it) for it in iterables)
    for it in iterables:
        it.extend([fillvalue] * (max_length - len(it)))

    # Create a deque for each iterable
    deques = [deque(it) for it in iterables]
    while True:
        result = [d[0] for d in deques if d]
        if not result:
            break
        yield tuple(result)
        for d in deques:
            if d:
                d.popleft()