Combining Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


This function takes an arbitrary number of iterable objects as arguments and returns an iterator that combines all the input iterables. If the input iterables have different lengths, the shorter ones will be filled with the specified `fillvalue`.


Technology Stack : itertools, zip_longest, is_iterable

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest

    def is_iterable(obj):
        try:
            iter(obj)
            return True
        except TypeError:
            return False

    # Determine the longest iterable
    max_length = 0
    for arg in args:
        if is_iterable(arg):
            max_length = max(max_length, len(arg))

    # Create an iterator for each argument
    iterators = [iter(arg) if is_iterable(arg) else iter([arg]) for arg in args]

    # Zip the iterators together and fill with fillvalue if necessary
    return zip_longest(*iterators, fillvalue=fillvalue)