Enhanced Zip Function for Unequal Length Iterables

  • Share this:

Code introduction


The function implements a similar functionality to the built-in `zip` function, but stops when the shortest input iterable is exhausted, rather than when the longest is. If the iterables have unequal lengths, missing values in the shorter iterables are filled in with `fillvalue`.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Like zip() but the iterator stops when the shortest input iterable is exhausted,
    instead of when the longest is. If the iterables have unequal lengths, missing values
    in the shorter iterables are filled in with fillvalue.
    """
    iterators = [iter(it) for it in iterables]
    while True:
        result = []
        for it in iterators:
            try:
                result.append(next(it))
            except StopIteration:
                result.append(fillvalue)
        if len(result) == 1 and result[0] is fillvalue:
            break
        yield tuple(result)