Creating an Aggregated Iterator with zip_longest

  • Share this:

Code introduction


The function is used to create an iterator that aggregates elements from each of the iterables. It returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. If the iterables 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):
    """
    This function is used to create an iterator that aggregates elements from each of the iterables.
    It returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or
    iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue.
    """
    # Using zip_longest from itertools module, which is a built-in module.
    from itertools import zip_longest

    return list(zip_longest(*args, fillvalue=fillvalue))                
              
Tags: