Normalizing Iterables to Same Length with Fill Value

  • Share this:

Code introduction


The function normalizes multiple iterable objects to have the same length, using a specified fill value for parts that are shorter.


Technology Stack : itertools, collections, operator

Code Type : Function

Code Difficulty : Intermediate


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

    def _pad(seq, fillvalue, n):
        return deque((item if i < len(seq) else fillvalue for i, item in enumerate(seq)), maxlen=n)

    n = max(map(len, args))
    iters = (_pad(iter(arg), fillvalue, n) for arg in args)
    return zip_longest(*iters)