Customizable Zip Function with Fillvalue

  • Share this:

Code introduction


The function implements functionality similar to the built-in `zip()` function, but it will automatically fill the shortest input iterable with `fillvalue` to maintain consistent length of the output iterable.


Technology Stack : itertools, collections, operator

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Similar to `zip()`, but the shortest input iterable is extended by `fillvalue` for
    the missing values.
    """
    from itertools import zip_longest
    from collections import deque
    from operator import itemgetter

    # Create a deque for each iterable to allow appending values at the end
    deques = [deque(iterable) for iterable in args]
    # Sort the deques based on the current first element
    deques.sort(key=itemgetter(0))
    # Initialize an empty list to store the output
    output = []

    # Loop until all deques are empty
    while deques:
        # Append the first element of each deque to the output list
        output.append([deque.popleft() for deque in deques if deque])
        # Extend the deque with fillvalue if it's empty
        deques = [deque if deque else deque([fillvalue]) for deque in deques]

    return output