Mimicking itertools.zip_longest with Deques

  • Share this:

Code introduction


This function uses `itertools.zip_longest` and `collections.deque` to mimic the functionality of `zip_longest`. It takes any number of iterable objects as arguments and returns an iterator that packs the elements of each iterable into tuples. If an iterable runs out of elements, it is filled with `fillvalue`.


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
    
    # Create a deque for each of the arguments to store the elements
    deques = [deque() for _ in args]
    # Initialize the index to track the iteration
    index = 0
    
    # Loop until all deques are empty
    while True:
        # Create a temporary list to hold the current set of elements
        temp = []
        for d in deques:
            # If the deque is empty, append the fillvalue
            if not d:
                temp.append(fillvalue)
            else:
                # Pop the first element from the deque
                temp.append(d.popleft())
        
        # If all deques are empty, break the loop
        if all(len(d) == 0 for d in deques):
            break
        
        # Yield the current set of elements
        yield tuple(temp)