Search code examples
pythonlambdareduceenumerate

Reduce with enumerate Python


I'm trying to get product of list where every element is multiplied by its index + 1. I tried with reduce and enumerate

value = reduce(lambda a, b: (a[0]+1)*a[1]*b[1], enumerate(list))

but it gives TypeError: 'int' object is not subscriptable. Is it possible to do it in one line?

Editv2

example of list [1,2,3]

desire output list[0]*1 * list[1]*2 * list[2]*3 = 36


Solution

  • Simplest:

    lst = [1,2,3]  # do not shadow `list`
    sum(i*v for i, v in enumerate(lst, 1))
    # 14
    

    Your reduce approach fails as it returns an int which is not the same type that it expects as its two inputs (tuple). You could do it with:

    reduce(lambda a, b: (a[0]*a[1] + b[0]*b[1], 1), enumerate(lst, 1))[0]
    # 14
    

    Note the (..., 1) structure of the lambda expression where the 1 serves as an auxiliary factor for the next step.

    Update: As you actually want the homogenous product of all the elements of your nested iterable, the following is simpler:

    from itertools import chain
    from operator import mul
    
    reduce(mul, chain(*enumerate(lst, 1)))
    # 36