Reputation: 147
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
Upvotes: 0
Views: 736
Reputation: 98
The trick is to make a new list and multiply through it.
Create a new list where a number at index i is i*list[i]
, indexing starting with 1:
>>> new_list = [a*b for a, b in enumerate(list, 1)]
>>> new_list
[1, 4, 9]
and multiply over your new list:
>>> reduce((lambda x, y: x*y), new_list)
36
In one line:
>>> reduce((lambda x, y: x*y), [a*b for a, b in enumerate(list, 1)])
36
Hope it helped :)
Note: Answer edited to meet OP's changes.
Upvotes: 1
Reputation: 73460
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
Upvotes: 4
Reputation: 331
ans = sum(i * x for i, x in enumerate(list, 1))
Not exactly what you are asking for, but it gives the desired result.
Upvotes: 0