Enhanced Zip Function for Shortest Iterable Termination

  • Share this:

Code introduction


This function is similar to the built-in `zip` function, but it continues to aggregate elements until the shortest iterable is exhausted, unlike `zip` which stops when the longest is exhausted. If there are missing elements in the iterator, they will be filled with the `fillvalue`.


Technology Stack : Built-in functions

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """
    Like zip(), returns an iterator that aggregates elements from each of the iterables.
    The iterator stops when the shortest iterable is exhausted, unlike zip(), which stops when the longest is exhausted.

    :param args: An arbitrary number of iterables.
    :param fillvalue: Value to use for missing values from shorter iterables.
    :return: An iterator that aggregates elements from each of the iterables.
    """
    iters = [iter(iterable) for iterable in args]
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                return
        yield tuple(result)