You can use a simple list comprehension, with slicing and sum
function, like this
>>> a = [0, 1, 2, 3, 4, 5]
>>> [sum(a[:i + 1]) for i in xrange(len(a))]
[0, 1, 3, 6, 10, 15]
Note: As paxdiablo and DSM noted, this method will be highly inefficient, as it has to find the sum of all the numbers which were seen before, again and again (for example, when you find sum of first 4 elements, you would be computing sum of first three elements as well, and implicitly sum of 2 elements as well). So, this is not suitable for larger lists.
The best way to solve this is by accumulating the results in a temporary variable and store it in the list like this
>>> result, temp = [], 0
>>> for item in a:
... temp += item
... result.append(temp)
...
>>> result
[0, 1, 3, 6, 10, 15]
Actually, if you are going to iterate over the sums and if the actual list is very big, then you can better make it as a generator function, like this
>>> def accumulate_sum(input_list):
... temp = 0
... for item in input_list:
... temp += item
... yield temp
...
and then iterate it to get the values one by one, like this
>>> for item in accumulate_sum([0, 1, 2, 3, 4, 5]):
... print(item)
...
0
1
3
6
10
15
You can also get the entire list, with list
function, like this
>>> list(accumulate_sum([0, 1, 2, 3, 4, 5]))
[0, 1, 3, 6, 10, 15]
FYI, Python 3.2+ has a function called itertools.accumulate
, which can be used like this
>>> from itertools import accumulate
>>> from operator import add
>>> a = [0, 1, 2, 3, 4, 5]
>>> list(accumulate(a, func=add))
[0, 1, 3, 6, 10, 15]
Or you can pass your own function which adds two numbers to accumulate
, like this
>>> list(accumulate([0, 1, 2, 3, 4, 5], func=lambda x, y: x + y))
[0, 1, 3, 6, 10, 15]