Zip Longest Function for Uneven Iterable Merging

  • Share this:

Code introduction


The function is used to merge multiple iterable objects of different lengths. If an iterable ends early, a specified fill value is used to continue.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    Zip the input iterables together, but if the iterables are of uneven length,
    fill in the missing values with the fillvalue.

    :param args: Variable length argument list of iterables.
    :param fillvalue: Value to use for missing values in the shorter iterables.
    :return: An iterator that aggregates elements from each of the iterables.
    """
    iterators = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == 0:
            break
        yield tuple(result)

# JSON representation