Combining Iterables with Fillvalue Using zip_longest

  • Share this:

Code introduction


This function uses `itertools.zip_longest` to combine multiple iterable objects into a list of tuples. If an iterable object has been traversed completely, `fillvalue` is used to fill in the missing values.


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

    def fill_deques(deques):
        max_len = max(len(d) for d in deques)
        for d in deques:
            while len(d) < max_len:
                d.append(fillvalue)

    deques = [deque(list(it)) for it in args]
    fill_deques(deques)
    return [tuple(d) for d in deques]