Ad

Looping Through A Nested List And Summing All Elements Of Each Internal List In Python

My problem is as follows: I have a list of lists named 'All_slips.' I would like to loop through each of the lists within the list and sum all of its elements, and then append these sums to a new list called 'Summed_list.' As such my desired output/solution would be a 'Summed_list' = [10,16,19]. A minimum reproducible program is provided below:

All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
Summed_list = []

for j in All_slips[j][] :
    counter = 0
    for i in All_slips[j][i] :
        counter += i
    Summed_list.insert(len(Summed_list),counter)
    
print (Summed_list)

I am new to python and i obtain a syntax error on line 4: 'for j in All_slips[j][]:'. What is the proper syntax to achieve what I stated above - I could not find another post that described this problem. Thanks in advance for your help.

Ad

Answer

summed_list = []
for sublist in All_slips:
    summed_list.append(sum(sublist))

That's all. You can also employ a list comprehension.

summed_list = [sum(sublist) for sublist in All_slips]
Ad
source: stackoverflow.com
Ad