zip_longest Function: Extending zip() with Fillvalue Support

  • Share this:

Code introduction


This function is similar to the built-in zip() function, but it fills in missing values with fillvalue until the longest iterable is exhausted. If all iterables are not of the same length, the shorter ones will be filled.


Technology Stack : Built-in function zip(), iterators, exception handling (StopIteration)

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    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 iterable is exhausted. If the *args are not all of the same
    length, missing values are filled-in with fillvalue.

    Args:
        *args: An arbitrary number of iterables.
        fillvalue: Value to use for missing values if the iterables are of unequal length.

    Returns:
        An iterator that aggregates elements from each of the iterables.
    """
    # Find the longest iterator
    iters = [iter(it) for it in args]
    longest = max(iters, key=len)
    for i, it in enumerate(iters):
        it.next()
    while True:
        result = []
        for it in iters:
            try:
                result.append(next(it))
            except StopIteration:
                iters[i] = iter([fillvalue])
                result.append(fillvalue)
        yield tuple(result)