Zip Sequences with Optional Fillvalue

  • Share this:

Code introduction


This function merges multiple sequences (lists, tuples, etc.) into a list of tuples. If the sequences have different lengths, the fillvalue is used to fill in missing values.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Zip equal length sequences together, but allow extra values from the longer sequences.
    The `fillvalue` argument is used for filling in missing values when the sequences are of unequal length.
    """
    # This function uses zip to combine sequences and itertools.zip_longest to handle sequences of different lengths.
    from itertools import zip_longest

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