Aggregating Elements from Iterables with FillValue

  • Share this:

Code introduction


The function aggregates elements from multiple iterable objects, returning pairs of elements with the same length. If an iterable runs out of elements early, fillvalue is used to fill in the missing values.


Technology Stack : Built-in library

Code Type : Function

Code Difficulty : Intermediate


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

    The iterator returns pairs of elements, as tuples of the same length;
    with missing values filled-in by fillvalue. The iterator stops when the shortest iterable is exhausted,
    even if the longer iterables still have unreturned items.

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

    Returns:
        An iterator that returns tuples with the aggregated elements.

    """
    # Determine the smallest iterable
    smallest_iterable = min((len(iterable) for iterable in iterables), default=0)
    # Create a list to hold the aggregated elements
    aggregated_elements = [iter(iterable) for iterable in iterables]
    # Loop through the smallest iterable and aggregate elements
    for _ in range(smallest_iterable):
        # Get the next element from each iterable, or fillvalue if it's exhausted
        next_elements = [next(aggregated_element, fillvalue) for aggregated_element in aggregated_elements]
        yield tuple(next_elements)