Python Implementation of zip_longest with Fillvalue

  • Share this:

Code introduction


This function implements similar functionality to zip_longest, merging multiple iterable objects into an iterator. If the shortest iterable runs out, it is filled with fillvalue.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest
    from collections import deque
    result = []
    max_len = max(len(lst) for lst in args)
    for i in range(max_len):
        result.append([arg[i] if i < len(arg) else fillvalue for arg in args])
    return result