Emulating itertools.zip_longest with Fillvalue

  • Share this:

Code introduction


This function emulates the functionality of itertools.zip_longest, which combines multiple iterable objects into a new iterable. If an iterable has fewer elements than others, it fills the missing values with a specified fillvalue.


Technology Stack : collections.deque, itertools.zip_longest

Code Type : Function

Code Difficulty : Intermediate


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

    # Helper function to create an iterator that repeats the fillvalue
    def repeat(fillvalue):
        while True:
            yield fillvalue

    # Create an iterator for each argument
    iterators = [iter(arg) for arg in args]
    # Create a deque to store the iterators
    queue = deque(iterators)

    # Create a generator that yields the next value from each iterator
    def next_values():
        for it in queue:
            try:
                yield next(it)
            except StopIteration:
                queue.remove(it)
                if fillvalue is not None:
                    queue.append(repeat(fillvalue).__next__())

    # Use zip_longest from itertools to create the final iterator
    return zip_longest(next_values())