Extended Zip Function with Fill Value Support

  • Share this:

Code introduction


This function implements an extended version of the zip function. It can fill in missing values when the lengths of the input iterators are different, with a default fill value of None.


Technology Stack : itertools, collections

Code Type : Iterator

Code Difficulty : Intermediate


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

    def pad(iterable, fillvalue):
        queue = deque(iterable, maxlen=len(iterable))
        return iter(lambda: queue.popleft() if queue else fillvalue, None)

    iters = [pad(iter(arg), fillvalue) for arg in args]
    while True:
        result = [next(iter_, fillvalue) for iter_ in iters]
        if any(fillvalue is not None and x is fillvalue for x in result):
            return
        yield result