Merging Iterables with Fillvalue Using itertools.zip_longest

  • Share this:

Code introduction


This function uses `itertools.zip_longest` to merge multiple iterable objects. If an iterable object is shorter, it is filled with `fillvalue` until all iterable objects are of the same length.


Technology Stack : itertools, collections, string

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import deque
    from string import ascii_lowercase
    
    def fill_deque_with_value(deq, value):
        while len(deq) < max(len(arg) for arg in args):
            deq.append(value)
    
    # Initialize deques with the first elements of each iterable
    deques = [deque([next(arg, fillvalue) for arg in args]) for _ in range(len(args))]
    
    # Fill deques with fillvalue until all are of the same length
    max_length = max(len(arg) for arg in args)
    for _ in range(max_length):
        fill_deque_with_value(deques, fillvalue)
    
    # Create the zip object
    zipped = zip_longest(*deques, fillvalue=fillvalue)
    
    return zipped