Combining Iterables with Fillvalue

  • Share this:

Code introduction


The function combines multiple iterable objects into a list. If some iterables are not long enough, it fills them with a specified fill value.


Technology Stack : itertools, collections, operator, math

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest
    from collections import deque
    from operator import itemgetter
    from math import ceil

    # Find the longest iterable to determine the number of fillvalues needed
    max_length = max(map(len, args), default=0)
    fill_count = max_length - max(map(len, args), default=0)

    # Pad the iterables with fillvalue
    padded_args = [deque(list(iterable) + [fillvalue] * fill_count) for iterable in args]

    # Use zip_longest to pair elements from each iterable
    paired_elements = zip_longest(*padded_args)

    # Convert the paired elements back into a list of lists
    result = [list(pair) for pair in paired_elements]

    return result