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.

Was it helpful?

Solution

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

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

OTHER TIPS

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

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

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

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top