Zip Multiple Iterables with Fill Value

  • Share this:

Code introduction


This function zips multiple iterable objects into one iterator, filling in missing values with a specified fill value if any of the iterables are of different lengths.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Zip the given iterables together, allowing for different lengths.

    Parameters:
    *iterables: An arbitrary number of iterables.
    fillvalue: The value to use for missing values in the shorter iterables.

    Returns:
    An iterator that aggregates elements from each of the iterables.

    Example:
    >>> list(zip_longest([1, 2, 3], ['a', 'b'], fillvalue='-'))
    [(1, 'a'), (2, 'b'), (3, '-')]
    """
    from itertools import zip_longest
    return zip_longest(*iterables, fillvalue=fillvalue)                
              
Tags: