time_interval = [4, 6, 12]
I want to sum up the numbers like [4, 4+6, 4+6+12]
in order to get the list t = [4, 10, 22]
.
I tried the following:
for i in time_interval:
t1 = time_interval[0]
t2 = time_interval[1] + t1
t3 = time_interval[2] + t2
print(t1, t2, t3)
4 10 22
4 10 22
4 10 22
Try this: accumulate function, along with operator add performs the running addition.
This is slighlty faster than the generator method above by @Ashwini for small lists
For larger lists, the generator is the way to go for sure. . .
I did a bench-mark of the top two answers with Python 3.4 and I found
itertools.accumulate
is faster thannumpy.cumsum
under many circumstances, often much faster. However, as you can see from the comments, this may not always be the case, and it's difficult to exhaustively explore all options. (Feel free to add a comment or edit this post if you have further benchmark results of interest.)Some timings...
For short lists
accumulate
is about 4 times faster:For longer lists
accumulate
is about 3 times faster:If the
numpy
array
is not cast tolist
,accumulate
is still about 2 times faster:If you put the imports outside of the two functions and still return a
numpy
array
,accumulate
is still nearly 2 times faster:Assignment expressions from PEP 572 (expected for Python 3.8) offer yet another way to solve this:
Without having to use Numpy, you can loop directly over the array and accumulate the sum along the way. For example:
Results in: