Enhanced Zip Function for Uneven-Length Iterables

  • Share this:

Code introduction


This function is similar to zip(), but it fills in missing values with fillvalue if the input iterables are of uneven length.


Technology Stack : zip, iter, next, StopIteration

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """
    Like zip(), but fills in missing values if the iterables are of uneven length.
    """
    iterators = [iter(arg) for arg in args]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        yield tuple(result)