Zip Longest Function: Combining Iterables with Fillvalue

  • Share this:

Code introduction


Combines elements from multiple iterable objects into a series of tuples. If the iterables have different lengths, missing values are filled with fillvalue.


Technology Stack : itertools, collections, operator

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    """
    Zip the elements of the provided iterables (args) together into a list of tuples.
    If the iterables are of uneven length, missing values are filled with fillvalue.
    """
    from itertools import zip_longest
    from collections import deque
    from operator import itemgetter

    # Create a deque for each iterable
    deques = [deque(iterable) for iterable in args]
    
    # Find the maximum length
    max_length = max(len(deque) for deque in deques)
    
    # Keep the deques in sync by truncating any that are too long
    for i in range(max_length):
        for deque in deques:
            if len(deque) > i:
                deque.append(fillvalue)
    
    # Zip the deques together
    return [tuple(deque[i] for deque in deques) for i in range(max_length)]