0

I have the following code:

y = [sum(x) for x in ([0, 1, 2], [10, 11, 12], [20, 21, 22])]

print(y)

The output is: [3, 33, 63]

What I am after is summing by position in each list, so the output I am wanting is:

[30, 33, 36]

0 + 10 + 20 = 30
1 + 11 + 21 = 33
2 + 12 + 22 = 36

What am I doing wrong?

vaultah
  • 44,105
  • 12
  • 114
  • 143
MarkS
  • 1,455
  • 2
  • 21
  • 36

2 Answers2

2

zip the lists first:

y = [sum(x) for x in zip([0, 1, 2], [10, 11, 12], [20, 21, 22])]

print(y)
# [30, 33, 36]
zwer
  • 24,943
  • 3
  • 48
  • 66
-1

If you want single sums by index you could write a method that gets you that:

def sum_by_index(array_2D,idx):
   s = 0
   for row in array_2D:
       s += row[idx]
   return s

If you want all the sums all at once you can do the same but all at once:

def sums_by_index(array_2D):
    s = array_2D[0]
    for row in array_2D[1:]:
        for i,entry in enumerate(row):
            s[i] += entry
    return s
Farmer Joe
  • 6,020
  • 1
  • 30
  • 40