Combining Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


The function uses `itertools.zip_longest` to combine multiple iterable objects into an iterator. If the longest iterable object is exhausted, the shorter ones are 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
    longest = max(map(len, args))
    result = [deque(list(x)[:longest]) for x in args]
    while result and result[0]:
        yield tuple(x.pop() for x in result)
        result = [deque(list(x)[:longest]) for x in result]