0
    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

2
  • because you keep creating new_list = [], then appending to it, then on the next iteration, doing new_list = [], which discards the previous list. Commented Mar 5, 2021 at 21:13
  • 2
    As an aside, having a list with single-element lists seems pretty pointless, why not just list(map(sum, data))? You coudl get what you posted originally, though, with something like [[sum(numbers)] for numbers in data] which you coudl get in your for-loop by just doing new_list.append([y]) Commented Mar 5, 2021 at 21:13

2 Answers 2

3

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]]
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.