Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading