Creating a Combined Iterator with Fillvalue Using zip_longest

  • Share this:

Code introduction


The function uses `itertools.zip_longest` to create an iterator that combines multiple iterables. It allows iteration over multiple iterables with the ability to fill in missing values with a specified fillvalue. Here, we use `collections.deque` to handle iterables of different lengths, ensuring all iterators can iterate to the same length.


Technology Stack : itertools, collections, operator

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import deque
    from operator import itemgetter

    # The zip_longest function is a variation of zip that allows iteration over multiple iterables
    # with the ability to fill in missing values with a specified fillvalue.
    # Here we use it to create a deque with the longest iterable to handle uneven iterable lengths.
    longest_iterable = max((len(x) for x in args), default=0)
    deques = [deque(list(x)[:longest_iterable]) for x in args]
    for _ in range(longest_iterable):
        yield tuple(itemgetter(*range(len(args)))(d.popleft() or fillvalue) for d in deques)