Faster way to sum a list of numbers than with a for-loop?


Question

Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?

Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user.

1
10
5/12/2009 2:27:08 AM

Accepted Answer

You can use sum() to sum the values of an array.

a = [1,9,12]
print sum(a)
32
5/12/2009 2:28:41 AM

Yet another way to sum up a list with the loop time:

    s = reduce(lambda x, y: x + y, l)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon