Extended `zip_longest` Function

  • Share this:

Code introduction


This function accepts an arbitrary number of iterable objects as arguments and returns an iterator. If the length of the input iterables is different, it fills the shorter iterables with fillvalue to make the lengths of all iterables the same.


Technology Stack : itertools, collections

Code Type : Function

Code Difficulty : Intermediate


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

    def _ensure_same_length(iterables):
        max_length = max(len(it) for it in iterables)
        return (deque(it, maxlen=max_length) for it in iterables)

    return zip_longest(*_ensure_same_length(args), fillvalue=fillvalue)