Python Generator for Padded Zip of Iterators

  • Share this:

Code introduction


This function creates a generator using `itertools.zip_longest` and `collections.deque`, which yields a tuple containing the next element from each input iterator. If an iterator is exhausted, it uses `fillvalue` to fill in the missing values.


Technology Stack : itertools, collections, deque

Code Type : Iterator generator

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest
    from collections import deque

    iterators = [deque(iter(arg)) for arg in args]
    while iterators:
        result = [next(it, fillvalue) for it in iterators]
        yield result
        iterators = [deque(list(it)[1:]) for it in iterators if list(it)[0] != fillvalue]