Python Implementation of itertools.zip_longest with Fillvalue Handling

  • Share this:

Code introduction


This function uses `itertools.zip_longest` and `collections.deque` to handle a variable number of iterable objects. When some iterable objects run out, it continues to output using the specified fill value.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


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

    def _fill_value(fillvalue):
        if isinstance(fillvalue, (list, tuple)):
            return [fillvalue] * len(args)
        return fillvalue

    fillvalues = _fill_value(fillvalue)
    iterators = [deque(iter(arg)) for arg in args]
    while iterators:
        values = []
        for i, iterator in enumerate(iterators):
            try:
                values.append(next(iterator))
            except StopIteration:
                iterators[i] = iter(fillvalues[i])
                values.append(next(iterators[i]))
        yield tuple(values)