Extending zip Function with Fillvalue for Inconsistent Lengths

  • Share this:

Code introduction


The function extends the built-in zip function, using fillvalue to fill in the missing values when the lengths of input iterable objects are inconsistent.


Technology Stack : itertools, collections, bisect

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Like zip() but the iterator stops when the shortest input iterable is exhausted,
    filling the rest with fillvalue.
    """
    from itertools import zip_longest
    from collections import deque
    from bisect import insort

    iterators = [deque(iterable) for iterable in iterables]
    results = []

    while iterators:
        for i, it in enumerate(iterators):
            if not it:
                iterators.pop(i)
                continue
            results.append(it.popleft())

        if not any(iterators):
            break

        # Rebuild the iterators for the next round
        iterators = [deque(vq) for vq in zip_longest(*iterators, fillvalue=fillvalue)]

    return results