Ad

How To Find The Sum Of Elements In Nested List?

- 1 answer

Below is the given list:

x = [[50,55,57],[50,55,58],[50,55,60],[50,57,58],[50,57,60],[50,58,60],[55,57,58],[55,57,60],[55,58,60],[57,58,60]]

What I need here is the sum of numbers of each nested list in a different list.

For e.g [162,163,.....]

Ad

Answer

Just loop through the items.

First you loop through the internal lists:

for lst in x:

Then you sum the items in the list using the sum method: total = sum(lst)

Together it looks like this:

new_list = list()
for lst in x:
    lst = sum(lst)
    new_list.append(total)

print(new_list)

Hope this helps.

Edit: I haven't used the sum method before. Which is why the two downvotes despite the program working fine.

Ad
source: stackoverflow.com
Ad