Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function combines multiple iterable objects into a list of tuples. If the iterables are of unequal length, missing values in the shorter iterables are filled with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Zip the elements of the provided iterables (args) together into a list of tuples.
    If the iterables are of uneven length, missing values are filled with fillvalue.

    :param args: Variable length argument list of iterables to zip.
    :param fillvalue: The value to use for missing values in shorter iterables.
    :return: A list of tuples, with the length of the returned list being the maximum of the lengths of the input iterables.
    """
    # The zip_longest function is similar to zip, but it allows for filling missing values with fillvalue
    # It is implemented using itertools.zip_longest, which is part of the Python standard library

    import itertools

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