Maximum itertools abuse!
Setup
from itertools import accumulate, chain, islice, tee
def pairwise(iterable):
'pairwise recipe from itertools docs'
it1, it2 = tee(iterable)
next(it2)
return zip(it1, it2)
list_a = [100, 5, 1, 2, 200, 3, 1, 300, 6, 6]
ind_list = [0, 4, 7]
Solution
ind_list.append(None)
result = list(chain.from_iterable(accumulate(islice(list_a, start, stop))
for start, stop in pairwise(ind_list)))
print(result)
Output
[100, 105, 106, 108, 200, 203, 204, 300, 306, 312]
The idea behind using itertools facilities whenever possible here is to avoid creating intermediary list-slices which unnecessarily consume memory.
~edit~~
Memory efficient Python 2.7 solution
from itertools import chain, islice, izip, tee
def pairwise(iterable):
'pairwise recipe from itertools docs'
it1, it2 = tee(iterable)
next(it2)
return izip(it1, it2)
def my_cumsum(iterable):
s = 0
for x in iterable:
s += x
yield s
list_a = [100, 5, 1, 2, 200, 3, 1, 300, 6, 6]
ind_list = [0, 4, 7]
ind_list.append(None)
result = list(chain.from_iterable(my_cumsum(islice(list_a, start, stop))
for start, stop in pairwise(ind_list)))
print(result)