0

can somebody help me with a code error.

What I need is to multiply 2nd and 3rd element of each list and then sum up four values (total result=431900) I've done it with a simple for loop:

lst = [['switch', '4', '12500'], ['hub', '1', '500'], ['router', '1', '1400'], ['jacks', '40', '9500']]

summ = 0
for i in lst:
    summ += int(i[1])*int(i[2])
print(summ)

But I wanted to improve it with a function or lambda:

from functools import reduce

result = reduce(lambda x, y: int(x[1])*int(x[2]))+(int(y[1])*int(y[2]), lst)
print(result)

It returns only first iteration (50500), on second x becomes None (y becomes the next list) and the program returns an error: TypeError: 'NoneType' object is not subscriptable.

I don't get why x becomes None, what is wrong here?

1
  • Why are you using reduce and not sum ? Commented Apr 24, 2022 at 11:11

1 Answer 1

1

Note that once you have summed, x is now a double and not a list thus not subscriptable. You thus need to make use of the initial (ie 3rd) parameter. Ans since its a sum, we start summing from 0.

reduce(lambda x, y: x + int(y[1]) * int(y[2]), lst, 0)
Out[230]: 431900
Sign up to request clarification or add additional context in comments.

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.