Product Calculation Using itertools.zip_longest

  • Share this:

Code introduction


This function takes any number of lists as arguments and combines them into a new list using `itertools.zip_longest`, filling with `fillvalue` if the lists have different lengths. For each element in the combined list, it calculates the product of the elements.


Technology Stack : itertools, operator, functools

Code Type : Function

Code Difficulty : Intermediate


                
                    
def zip_longest(*args, fillvalue=0):
    from itertools import zip_longest as zip_longest_from_itertools
    from operator import mul
    from functools import reduce

    def calculate_product(sequence):
        return reduce(mul, sequence, 1)

    max_len = max(len(lst) for lst in args)
    zipped = zip_longest_from_itertools(*args, fillvalue=fillvalue)
    result = [calculate_product(item) for item in zip_longest_from_itertools(*zipped)]
    return result