not-too-smatr
not-too-smatr

Reputation: 599

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

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

Answers (5)

Alex
Alex

Reputation: 44709

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

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

Upvotes: 4

Tal Pressman
Tal Pressman

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

Chris Bartow
Chris Bartow

Reputation: 15111

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

a = [1,9,12]
print sum(a)

Upvotes: 36

Annath
Annath

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

clawr
clawr

Reputation: 7895

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

Upvotes: 1

Related Questions