Emulation of itertools.zip_longest with Fillvalue

  • Share this:

Code introduction


This function emulates the functionality of itertools.zip_longest, which merges multiple iterable objects (args) into a single iterator. If the iterables are of uneven length, missing values are filled with the fillvalue.


Technology Stack : itertools, collections, typing

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    Zip the elements of the provided iterables (args) together into a single iterable.
    If the iterables are of uneven length, missing values are filled with the fillvalue.
    """
    from itertools import zip_longest
    from collections import deque
    from typing import Any, Iterable, Iterator

    def fill(iterable, fillvalue):
        return (x for x in iterable) + (fillvalue,)

    def interleave(*iterables):
        iters = [deque(iterable) for iterable in iterables]
        while iters:
            for iterable in iters[:]:
                try:
                    yield iterable.popleft()
                except IndexError:
                    iters.remove(iterable)

    longest = max(len(it) for it in args)
    for _ in range(longest):
        yield from interleave(*(fill(it, fillvalue) for it in args))