Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 972
not-too-smatr Avatar asked May 12 '09 02:05

not-too-smatr


People also ask

Is sum faster than for loop?

When you wrote the total function, we mentioned that R already has sum to do this; sum is much faster than the interpreted for loop because sum is coded in C to work with a vector of numbers. Many of R's functions work this way; the loop is hidden from you in C.

How do you sum all numbers in a list in Python?

sum() function in Python Sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. Syntax: sum(iterable, start) iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.


2 Answers

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

a = [1,9,12]
print sum(a)
like image 134
Chris Bartow Avatar answered Oct 04 '22 02:10

Chris Bartow


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.

like image 41
Annath Avatar answered Oct 04 '22 02:10

Annath