Handling Different Length Iterables with zip_longest

  • Share this:

Code introduction


This function uses `itertools.zip_longest` and `collections.deque` to create a function that can handle iterables of different lengths. If the iterables are of different lengths, it fills with the `fillvalue`.


Technology Stack : itertools, collections, deque, zip_longest

Code Type : Function

Code Difficulty : Intermediate


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

    def _interleave_fillvalues(fixed_length, fillvalue):
        return (deque([fillvalue] * fixed_length), fillvalue)

    def _zip_longest(*iterables, fillvalue=None):
        iters = [iter(it) for it in iterables]
        iters_with_fill = [zip_longest(it, _interleave_fillvalues(len(it), fillvalue), fillvalue=fillvalue) for it in iters]
        return zip(*iters_with_fill)

    return _zip_longest(*args, fillvalue=fillvalue)