Handling Iterables of Different Lengths with zip_longest

  • Share this:

Code introduction


This function uses `itertools.zip_longest` and `collections.deque` to handle iterables of different lengths. When the longest iterable ends, `fillvalue` is used to fill shorter sequences.


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(len(lst) for lst in args)
    for i in range(longest):
        yield [deque(lst)[i] for lst in args if i < len(lst)]