Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function combines elements from multiple iterable objects, and if an iterable object is shorter than the others, it fills with a specified fillvalue.


Technology Stack : Built-in functions zip, list comprehension

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    zip_longest_list = []
    for i in range(max(map(len, args))):
        new_tuple = tuple(arg[i] if i < len(arg) else fillvalue for arg in args)
        zip_longest_list.append(new_tuple)
    return zip_longest_list