Zip Longest Iterables with Fillvalue

  • Share this:

Code introduction


The function is used to merge multiple iterable objects into a list of tuples. If the lengths of the iterators are different, the values of the longest iterator are used for the output, and the values of the shorter iterators are filled with `fillvalue`.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    """
    Zip the elements of the iterable(s) together into a list of tuples.
    The iterator(s) must have the same length. If the iterators are of different lengths,
    the longest iterator's values are used for the output, and the shorter iterators'
    values are filled with `fillvalue`.
    """
    # Using itertools.zip_longest from Python's standard library
    from itertools import zip_longest

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