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
  • 40,483
  • 12
  • 109
  • 137
MarkS
  • 1,383
  • 1
  • 18
  • 30

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
  • 23,595
  • 3
  • 41
  • 57
-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
  • 5,822
  • 1
  • 26
  • 38