Creating an Aggregated Iterator with Fillvalue

  • Share this:

Code introduction


Create an iterator that aggregates elements from each of the iterables. The iterator returns pairs of the form (i, val), where i is the index of the element from the iterable and val is the element obtained from the iterable. The iterator stops when the shortest iterable is exhausted, applying fillvalue for the missing values.


Technology Stack : itertools.zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Return an iterator that aggregates elements from each of the iterables.
    The iterator returns pairs of the form (i, val), where i is the index of the element
    from the iterable and val is the element obtained from the iterable.
    The iterator stops when the shortest iterable is exhausted, applying fillvalue
    for the missing values.
    """
    # Importing from the Python Standard Library
    from itertools import zip_longest as it_zip_longest

    def wrapper(*args, fillvalue=None):
        return it_zip_longest(*args, fillvalue=fillvalue)

    return wrapper

# JSON representation of the function