Handling Variable-Length Iterables with Fill Values

  • Share this:

Code introduction


This function utilizes `itertools` and `collections` modules' `zip_longest` and `deque` functionalities to handle iterables of different lengths and fill the shorter sequences with a specified fill value.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


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

    # Create a deque for each of the input iterables
    deques = [deque() for _ in args]
    # Calculate the maximum length of the input iterables
    max_length = max(len(d) for d in deques)
    # Fill the deques with fillvalue until they all have the same length
    for _ in range(max_length - len(d) for d in deques):
        for d in deques:
            d.append(fillvalue)
    # Zip the deques together
    return zip_longest(*deques)