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

2
  • 1
    Use sum instead of shadowing it. Commented Aug 21, 2021 at 22:30
  • from stackoverflow.com/a/952946/16668765 you can try sum(sum(a, [])) oh it's super inefficient but fun Commented Aug 21, 2021 at 22:47

1 Answer 1

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

2 Comments

Yeah, map also does the same; however, I'm fond of the comprehension.
Yes, it's comprehension but not the list comprehension, it's generator expression, and people also refer to it as generator comprehension.

Your Answer

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