Home > OS >  How to sum second array in python
How to sum second array in python

Time:11-19

I want to sum a 2d list. Example: x==[[1, 2],[3, 4],[5, 6]]

a solution should lool like: sum_2d = [3, 7, 11]

I tried this: y = sum(sum(x,[])) but that sums all the numbers.

Thanks for any advice.

CodePudding user response:

x=[[1, 2],[3, 4],[5, 6]]

[sum(y) for y in x]

#output
[3, 7, 11]

using list comprehension

CodePudding user response:

You can use a for loop to iterate over x, and use sum() at each row of x:

x = [[1, 2], [3, 4], [5, 6]]

sum_2d = []

for i in x:
    sum_2d  = [sum(i)]
    
print(sum_2d)
  • Related