Creating a Zip Longest Function

  • Share this:

Code introduction


The function takes any number of iterables (such as lists, tuples) and returns an iterator that aggregates elements from each of the iterables. It stops when the shortest iterable is exhausted, filling in missing values with a specified fillvalue.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    This function takes any number of iterables (e.g., lists, tuples) and returns 
    an iterator that aggregates elements from each of the iterables. It stops when 
    the shortest iterable is exhausted, filling in missing values with a specified 
    fillvalue.

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

    Returns:
    An iterator that aggregates elements from the iterables.

    Example:
    >>> list(zip_longest([1, 2, 3], [4, 5], fillvalue=0))
    [1, 4, 0], [2, 5, 0], [3, None, 0]
    """
    from itertools import zip_longest
    return zip_longest(*args, fillvalue=fillvalue)                
              
Tags: