Zip Longest Iterator for Aggregating Iterables

  • Share this:

Code introduction


This function is used to merge multiple iterable objects into one iterator. If the iterable objects are of different lengths, missing values will be filled with fillvalue.


Technology Stack : Built-in libraries

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Return an iterator that aggregates elements from each of the iterables.

    Returns a new iterator, zipped together element by element from each of the iterables. If the iterables are of uneven
    length, missing values are filled-in with fillvalue.

    :param *args: An arbitrary number of iterables.
    :param fillvalue: The value to use for missing values if the iterables are of uneven length.
    :return: An iterator that aggregates elements from each of the iterables.
    """
    # Determine the longest iterable
    iters = [iter(arg) for arg in args]
    longest = max(len(it) for it in iters, default=0)

    for i in range(longest):
        yield [next(it, fillvalue) for it in iters]