Python Implementation of zip_longest with fillvalue

  • Share this:

Code introduction


This function implements a similar function as zip_longest. It accepts multiple iterable objects as parameters and, if the lengths of the iterators are inconsistent, it fills to the length of the shortest iterator using fillvalue.


Technology Stack : itertools, collections, typing

Code Type : Function

Code Difficulty : Intermediate


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

    T = TypeVar('T')

    def _filler(dq):
        while True:
            try:
                yield dq.popleft()
            except IndexError:
                yield fillvalue

    iters = [iter(arg) for arg in args]
    deques = [deque(iterable) for iterable in iters]
    fillers = [deque(_filler(dq)) for dq in deques]

    while True:
        try:
            for dq in deques:
                dq.append(next(fillers[dq]))
            yield [next(dq) for dq in deques]
        except StopIteration:
            return