Combining Iterables with Fillvalue

  • Share this:

Code introduction


Combine multiple iterables into a list of tuples, filling with a specified value if the iterables are of unequal length.


Technology Stack : Combine multiple iterables into a list of tuples, filling with a specified value if the iterables are of unequal length.

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """Zip the input iterables (elements of *args) together into a list of tuples. 
    The iterables must have the same length; otherwise, the shorter iterables are padded with fillvalue.

    Args:
        *args: Variable length argument list. Each argument is an iterable.
        fillvalue: Value to use for padding when the iterables are of unequal length.

    Returns:
        A list of tuples, padded with fillvalue where necessary.

    Example:
        >>> list(zip_longest([1, 2, 3], [4, 5], fillvalue=0))
        [(1, 4), (2, 5), (3, 0)]
    """
    from itertools import zip_longest
    return list(zip_longest(*args, fillvalue=fillvalue))