Combining Iterables with FillValue

  • Share this:

Code introduction


This function combines multiple iterable objects (like lists or tuples) into a single iterable. If the iterables have different lengths, missing values are filled with `fillvalue`.


Technology Stack : zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    This function zips multiple iterables (like lists or tuples) together into a single iterable.
    If the iterables are of unequal length, missing values are filled with `fillvalue`.
    """
    iterators = [iter(arg) for arg in args]
    while True:
        result = []
        for iterator in iterators:
            try:
                result.append(next(iterator))
            except StopIteration:
                result.append(fillvalue)
        yield result

# JSON output                
              
Tags: