Iterating Over Uneven Length Iterables with zip_longest

  • Share this:

Code introduction


This function uses the zip_longest function from the itertools library to merge multiple iterable objects. If these iterable objects are of uneven length, missing values are filled with fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """
    Return an iterator that aggregates elements from each of the iterables.

    If the iterables are of uneven length, missing values are filled-in with fillvalue.

    Args:
        *iterables: An arbitrary number of iterables.
        fillvalue: Value to use for missing values if the iterables are of uneven length.

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

    Example:
        >>> list(zip_longest([1, 2, 3], ['a', 'b'], fillvalue='x'))
        [(1, 'a'), (2, 'b'), (3, 'x')]

    """
    from itertools import zip_longest

    return zip_longest(*iterables, fillvalue=fillvalue)                
              
Tags: