Combining Iterables with Fillvalue using zip_longest

  • Share this:

Code introduction


This function accepts an arbitrary number of iterable objects as arguments and returns an iterator that combines the input iterables into a new iterator. Shorter inputs are filled with a fill value until all inputs are exhausted.


Technology Stack : itertools, collections, typing

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=None):
    from itertools import zip_longest
    from collections import deque
    from typing import Any, Iterable, Iterator

    def fill_deques(deques):
        for i, deque_ in enumerate(deques):
            while len(deque_) < len(args[i]):
                deque_.append(fillvalue)

    def make_deques():
        return [deque(list(args[i])) for i in range(len(args))]

    deques = make_deques()
    fill_deques(deques)
    return [deque_.popleft() for deque_ in deques]