Combining Iterables with FillValue Support

  • Share this:

Code introduction


This function combines an arbitrary number of iterable objects. If an iterable object is exhausted, it fills in the missing values with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest

    def zip_longest_inner(*args, fillvalue=None):
        # This is a helper function to handle the actual zipping logic
        iters = [iter(arg) for arg in args]
        while True:
            result = []
            for it in iters:
                try:
                    result.append(next(it))
                except StopIteration:
                    result.append(fillvalue)
            if not any(result):
                break
            yield result

    return zip_longest_inner(*args, fillvalue=fillvalue)

# JSON description                
              
Tags: