Optimized Zip Longest with Filling for Iterables

  • Share this:

Code introduction


This function uses the `itertools.zip_longest` to merge multiple iterable objects. If an iterable is shorter than the others, it is filled with `fillvalue`. Here, `collections.deque` is used to optimize operations on the longest iterable.


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

    # Helper function to ensure that the longest iterable is the one being filled
    def fill_iterable(iterable, fill_value):
        iterator = iter(iterable)
        while True:
            try:
                yield next(iterator)
            except StopIteration:
                yield fill_value

    # Find the longest iterable
    longest_iterable = max(args, key=len)

    # Create a deque of the longest iterable to allow popping from the back
    longest_iterable_deque = deque(longest_iterable)

    # Use zip_longest to iterate over the iterables, filling with None or the provided fillvalue
    return zip_longest(fill_iterable(longest_iterable_deque, fillvalue), *args)