Python#s zip_longest Function: Aggregating Iterables with Fillvalues

  • Share this:

Code introduction


This function takes any number of iterable objects and returns an iterator that aggregates elements from each of the iterables. It returns elements as tuples containing one element from each of the iterables. If the iterables are of uneven length, missing values are filled in with `fillvalue`.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    This function takes any number of iterables and returns an iterator that aggregates elements from each of the iterables.
    It returns elements as tuples containing one element from each of the iterables.
    If the iterables are of uneven length, missing values are filled-in with `fillvalue`.
    """
    args = [iter(arg) for arg in args]
    while True:
        yield tuple(next(arg, fillvalue) for arg in args)