Reputation: 599
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.
Upvotes: 13
Views: 29003
Reputation: 44709
Yet another way to sum up a list with the loop time:
s = reduce(lambda x, y: x + y, l)
Upvotes: 4
Reputation: 7317
For a general list, you have to at least go over every member at least once to get the sum, which is exactly what a for loop does. Using library APIs (like sum) is more convenient, but I doubt it would actually be faster.
Upvotes: -1
Reputation: 15111
You can use sum() to sum the values of an array.
a = [1,9,12]
print sum(a)
Upvotes: 36
Reputation: 1262
Well, I don't know if it is faster but you could try a little calculus to make it one operation. (N*(N+1))/2 gives you the sum of every number from 1 to N, and there are other formulas for solving more complex sums.
Upvotes: 1