Combining Iterables with Fillvalue Using itertools.zip_longest

  • Share this:

Code introduction


This function uses the zip_longest method from the itertools module to combine elements from multiple iterable objects. If the iterable objects are of uneven length, missing values are filled in with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Returns an iterator that aggregates elements from each of the iterables.
    If the iterables are of uneven length, missing values are filled-in with
    fillvalue. Default fillvalue is None.
    """
    # Using itertools.zip_longest from the standard library
    from itertools import zip_longest

    def iterables():
        for iterable in args:
            for element in iterable:
                yield element

    return zip_longest(*iterables(), fillvalue=fillvalue)

# JSON representation of the code                
              
Tags: