Combining Iterables with Fillvalue

  • Share this:

Code introduction


This custom function takes multiple iterable objects as arguments and returns a tuple, where each element is a combination of the elements from the input iterables. If the iterables have different lengths, it fills the shorter ones with a fillvalue.


Technology Stack : zip, max, len, list comprehension

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    Fill values in shorter iterables so that all iterables have the same length.
    """
    max_len = max(len(a) for a in args)
    return zip(*[i[:max_len] for i in args])

# JSON representation