0

Pls can someone help me out on how to sum a nesting list like this

cash = [10, 20, 30, 100, [200, [400], 800], 80]

First question is to add 200 and 800 and I was able to get that. Through this method

print(cash[4][0] + cash[4][2])

And the output was 1000 which is very correct.

The second question is to sum 400 and 80

But when I try this method

print(cash[4][1] + cash[5])

I got error message that it can only concatenate list and not int. So am stuck here . If am able to solve this then the third questions will be easy to answer

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
NathCoded
  • 1
  • 1
  • 1
    `cash[4][1][0] + cash[-1]` You simply didn't index into the `[400]` list – Schalton Oct 04 '21 at 21:47
  • Wanted to show you that `-1` can be used for the last item in the list; you can also do things like `sum(cash[1:2])` to slice the list and add `20 + 30` – Schalton Oct 04 '21 at 21:48
  • I disagree with whoever closed it, but here's a more detailed answer: `cash[4] = [200, [400], 800]`, `cash[4][1] = [400]`, `cash[4][1][0] = 400` and `cash[5] = cash[-1] = 80` so: `cash[4][1][0] = 400 + cash[-1]` – Schalton Oct 04 '21 at 21:51
  • Flatten the list, and then sum it. As for the issue in the code you tried, that's simply a typo. You should try to learn some basic debugging skills. For example, if you get a type error trying to add two things, you should try to figure out the types (and values) of the things that were being added. Here, you can check `cash[4][1]` and find that it is `[400]`, not `400`. – Karl Knechtel Oct 04 '21 at 21:53
  • It's also useful to learn proper terminology, in order to describe your problems better and get help more easily. here, for example, "call the value" makes no sense whatsoever. – Karl Knechtel Oct 04 '21 at 21:54

0 Answers0