Combining Iterables with Fillvalue

  • Share this:

Code introduction


This function is used to concatenate multiple iterable objects (such as lists, tuples, etc.), and fill missing values with fillvalue if the length of some iterable objects is insufficient.


Technology Stack : itertools.zip_longest, collections.deque

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*iterables, fillvalue=None):
    """Function to zip multiple iterables (lists, tuples, etc.) and fill missing values with fillvalue.

    Args:
        *iterables: Variable number of iterable arguments.
        fillvalue: Value to use for missing values in shorter iterables.

    Returns:
        Zipped iterator that combines elements from the iterables. Missing values in shorter iterables are filled with fillvalue.

    """
    from itertools import zip_longest
    from collections import deque

    def fill_values(iterable):
        iterator = iter(iterable)
        for element in iterator:
            yield element

    for iterable in iterables:
        if not hasattr(iterable, '__iter__'):
            iterable = [iterable]

    zipped = zip_longest(fill_values(iterable) for iterable in iterables)

    # Convert tuples back to lists for the final output
    return [list(tuple) for tuple in zipped]