Custom Zip Longest Implementation

  • Share this:

Code introduction


This function implements a similar functionality to itertools.zip_longest, merging multiple iterable objects into one iterator. If a certain iterable is shorter than the others, 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

    # Helper function to ensure that each iterator is the same length as the longest one
    def fill_iter(iterable, fillvalue):
        d = deque(iterable)
        while d:
            yield d.popleft() if d[0] is not None else fillvalue

    # Use zip_longest from itertools to zip the arguments together
    # and fill missing values with fillvalue
    longest_iter = fill_iter(args[0], fillvalue)
    zipped = zip_longest(*args, fillvalue=fillvalue)

    # Return the zipped values as a list
    return list(zipped)