Python Implementation of zip_longest with Fillvalue

  • Share this:

Code introduction


This function implements a similar functionality to zip_longest, merging multiple iterable objects into an iterator. If a certain iterable object is not long enough, it is filled with fillvalue.


Technology Stack : itertools, collections, typing

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest
    from collections import deque
    from typing import Any
    
    def fill_deques(deques, fillvalue):
        for i in range(len(deques)):
            while len(deques[i]) < len(args[i]):
                deques[i].append(fillvalue)
    
    deques = [deque(list(x)) for x in args]
    fill_deques(deques, fillvalue)
    
    for i in range(len(args[0])):
        yield [deque[i] for deque in deques]