views:

483

answers:

5

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.

+15  A: 

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

a = [1,9,12]
print sum(a)
Chris Bartow
A: 

If each term in the list simply increments by 1, or if you can find a pattern in the series, you could find a formula for summing n terms. For example, the sum of the series {1,2,3,...,n} = n(n+1)/2

Read more here

TenebrousX
A: 

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.

Annath
A: 

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.

Tal Pressman
sum() will be faster than a for loop because it's written in C.
musicfreak
@musicfreak:not exactly, it will be faster because it avoids the overhead of a for loop (variable assignments and method calls)
Algorias
Which is because it's written in C... Either way it's faster.
musicfreak
Right, it's not like sum() isn't using a for loop in C. It's just that C is faster than python (for the parts of python not implemented in C).
tfinniga
+2  A: 

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

    s = reduce(lambda x, y: x + y, l)
Alex
You should use operator.add instead of the lambda. Summing the first 100000 numbers is 34ms with the lambda but only 19ms with operator.add. (Sum is better than both at 15ms).
Kiv