Tompan
Tompan

Reputation: 27

How to sum up individual nested lists in python

    data = [[1, 1, 0, 1, 1, 0, 0], [0, 0, 1, 0, 0, 1, 0], [0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 2, 3], [1, 1, 2, 0, 1, 1, 0], [1, 0, 0, 2, 1, 1, 2]]

Hello, I have this list with nested lists called data. I would like to sum up the indivual nested lists only so the output is:

    [[4],[2],[2],[0],[0],[0],[0],[0],[6],[6],[7]]

I tried to do this:

    for numbers in data:
            new_list = []
            y = sum(numbers)
            new_list.append(y) 
     print (new_list)

However, this only gives the sum of the last nested list, because for every for-loop the new_list seems to "reset".

Thanks

Upvotes: 0

Views: 52

Answers (2)

Alain T.
Alain T.

Reputation: 42133

Not sure why you would want each sum to be a single element list but you can do it in a list comprehension:

[ [sum(sl)] for sl in data ]
                         
[[4], [2], [2], [0], [0], [0], [0], [0], [6], [6], [7]]

Upvotes: 3

Daniyar Aubekerov
Daniyar Aubekerov

Reputation: 273

The reason is that your new_list must be outside of the loop. Right now, after each iteration, you are overwriting your new_list. Also, if you want each element to be a list you will need to change to [y] Try to:

new_list = []
for numbers in data:
            y = sum(numbers)
            new_list.append([y]) 
 print (new_list)

Also, if you want to use python's list comprehension feature you can do:

new_list = [[sum(numbers)] for numbers in data]

Upvotes: 1

Related Questions