Merging Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


This function takes multiple iterable objects as arguments and merges them into an iterator using the `itertools.zip_longest` function. If the iterables have different lengths, it uses a `fillvalue` to pad the shorter ones.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import deque
    
    def fill_deques(deques, fill_value):
        for i in range(len(deques)):
            while len(deques[i]) < len(args[i]):
                deques[i].append(fill_value)
    
    # Initialize deques for each argument
    deques = [deque(list(arg)) for arg in args]
    
    # Fill deques with fillvalue until the longest one
    fill_deques(deques, fillvalue)
    
    # Zip the deques together
    return zip_longest(*deques)