Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function combines multiple iterable objects into a list of tuples, where each tuple contains the next item from each iterable. If the iterables are of unequal length, missing values are filled with the `fillvalue`.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """
    This function takes an arbitrary number of iterable arguments and returns a list of tuples,
    where each tuple contains the next item from each of the argument iterables. If the iterables
    are of unequal length, missing values are filled with the `fillvalue`.

    Parameters:
    *args: An arbitrary number of iterable arguments.
    fillvalue: The value to use for missing values in the shorter iterables.

    Returns:
    A list of tuples with the next item from each iterable.
    """
    from itertools import zip_longest
    return list(zip_longest(*args, fillvalue=fillvalue))                
              
Tags: