Python Zip Longest with Fillvalue

  • Share this:

Code introduction


Combines the input sequences into a list of tuples, using `fillvalue` to fill in missing values in sequences that are shorter than the longest one.


Technology Stack : itertools.zip_longest

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    Zips the input sequences together into a list of tuples, using `fillvalue` for sequences
    that are shorter than the longest sequence.

    Args:
        *args: An arbitrary number of sequences to be zipped.
        fillvalue: The value to use for filling in missing values in the shorter sequences.

    Returns:
        A list of tuples containing the elements from the input sequences.

    """
    from itertools import zip_longest

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