0

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

9
  • 1
    Can you give an example list and the result you want? Commented Mar 16, 2020 at 17:09
  • there is no positions for 'a' it might be single number check it once Commented Mar 16, 2020 at 17:10
  • 1
    You clearly want the sum of those products! Otherwise you will always get 0, if multiply index 0 somewhere in there. Commented Mar 16, 2020 at 17:15
  • 2
    Why not just sum and a generator expression: sum(index * value for index, value in enumerate(data))? Commented Mar 16, 2020 at 17:17
  • 1
    Instead of sum do numpy.prod([i*v for i, v in enumerate(lst, 1)]) Commented Mar 16, 2020 at 17:35

3 Answers 3

4

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
Sign up to request clarification or add additional context in comments.

4 Comments

OP wants index + 1.
@blueteeth Adapted ;)
that's what I tried to achive .Still I wanted the product not sum but it is enough to replace '+' with '*' and works, so thank you for help
Instead of sum do numpy.prod([i*v for i, v in enumerate(lst, 1)])
1

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.

Comments

0
ans = sum(i * x for i, x in enumerate(list, 1))

Not exactly what you are asking for, but it gives the desired result.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.