Combining Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


This function combines several iterable objects (such as lists, tuples, etc.) into a single iterable that aggregates elements from the iterables in parallel. If an iterable has fewer elements than others, the `fillvalue` parameter can be used to fill in missing values.


Technology Stack : itertools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=()):
    """Combine several iterables (lists, tuples, etc.) into a single iterable that aggregates elements from the iterables in parallel.

    Args:
        *args: 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], [4, 5], [6], fillvalue=0))
        [(1, 4, 6), (2, 5, 0), (3, 0, 0)]
    """
    from itertools import zip_longest

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