'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.



Solution 1:[1]

if you want to go with functional programming way, here is one solution

>>> All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
>>> summed_list= list(map(sum , All_slips))
>>> summed_list
[10, 16, 19]

otherwise, below would be easy list compreghension one solution

summed_list = [sum(sub_list) for sub_list in All_slips]

if you want to go with for loop, then store sum of a sublist in a varibale for a single iteration and then save this in summed_list

suumed_list = []
for sub_list in All_slips:
    sublist_sum = 0
    for val in sub_list:
        sublist_sum+= val
    summed_list.append(sublist_sum)

Solution 2:[2]

Take a look at the docs for an introduction to for loops.

A typical for loop in python has a for item in iterable type of syntax and you can access the members of the iterable using the variable item within the loop.

In your case, if you want to maintain the two loops-

for inner_list in All_slips:
    inner_sum = 0
    for element in inner_list:
        inner_sum = inner_sum + element
    summmed_list.append(inner_sum)

Of course, you don't really have to maintain the two loops as sum is a built in function in python -

for inner_list in All_slips:
    inner_sum = sum(inner_list)
    summed_list.append(inner_sum)

You can take it a step further by using a list comprehension -

summed_list = [sum(inner_list) for inner_list in All_slips]

Solution 3:[3]

You can use the built-in map function. It maps a function to a list of iterables.

map(function, list-of-iterables)

Since Python 3 this will get you a map-generator, therefore you might want to make it a list, set or whatever iterable you prefer.

list(map(sum, list-of-iterables))

So in your case:

>>> All_slips = [[1,2,3,4],[1,3,5,7],[1,2,7,9]]
>>> summed_list = list(map(sum, All_slips))
>>> print(summed_list)
[10, 16, 19]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sahasrara62
Solution 2 Mortz
Solution 3 Alex