Implementation of zip_longest with Fillvalue

  • Share this:

Code introduction


This function implements a similar functionality to zip(), but the length of the output sequence is determined by the shortest input sequence. If a sequence reaches the end first, it is filled with fillvalue.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Like zip() but the shortest input sequence determines the length of the output sequence
    """
    from itertools import zip_longest
    from collections import deque

    def pairwise(iterable):
        "s -> (s0, s1), (s1, s2), (s2, s3), ..."
        a = iter(iterable)
        return zip(a, a)

    iters = [iter(args[i]) for i in range(len(args))]
    while True:
        batch = [next(i, fillvalue) for i in iters]
        if all(x is fillvalue for x in batch):
            break
        for i in range(1, len(batch), 2):
            for pair in pairwise(batch[i]):
                yield batch[0], pair