Extended Zip Function with Fillvalue

  • Share this:

Code introduction


This function is similar to the built-in zip() function, but it fills the shortest input iterable with fillvalue.


Technology Stack : itertools, collections, functools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Similar to zip(), but the shortest input iterable is extended by fillvalues
    """
    from itertools import zip_longest
    from collections import deque
    from functools import reduce

    def fill_values(fillvalue):
        return lambda it: (fillvalue if not hasattr(it, '__next__') else next(it))

    def fill_values_iter(fillvalue):
        return (fill_values(fillvalue) for _ in range(len(args)))

    def create_iter(fillvalue):
        return reduce(lambda it, f: (f(it),), fill_values_iter(fillvalue), args)

    return create_iter(fillvalue)