0

Hello is there better way to sum multiple arrays? Because what I did is nested loop and i am not fan of this solution.

a = [1,2,8,7,4], [6,7,2,1,6], [7,5,1,2,3]
sum = []
total = 0

for i in a:
    for j in i: 
        total = total + j
        sum.append(total)

print(sum[-1])

expected output: 62

1 Answers1

1

You can just use sum inside the comprehension (generator expression) for each sub-lists in the list, then pass it to the sum builtin again.

>>> sum(sum(i) for i in a)
62

Or, map each sub-list to the sum, and pass it to sum

>>> sum(map(sum, a))
62
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • Yeah, map also does the same; however, I'm fond of the comprehension. – ThePyGuy Aug 21 '21 at 22:38
  • Yes, it's comprehension but not the list comprehension, it's generator expression, and people also refer to it as generator comprehension. – ThePyGuy Aug 21 '21 at 22:39