-1

Suppose I have two lists of the same size in Python, the first:

[100, 200, 300, 400]

and I want the other to be:

[0, 100, 300, 600] 

which is each element in the 2nd list equals the sum of all previous elements in the first.

Is there a built-in Python function that does such an operation on a list? Or do I have to think about an algorithm to do it?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

2

If you use Python 3.2+, you can use itertools.accumulate:

>>> import itertools
>>>
>>> a_list = [100, 200, 300, 400]
>>> list(itertools.accumulate([0] + a_list[:-1]))
[0, 100, 300, 600]

UPDATE

To avoid creation of temporary list, use itertools.islice, itertools.chain:

>>> from itertools import chain, accumulate, islice
>>>
>>> a_list = [100, 200, 300, 400]
>>> list(accumulate(chain([0], islice(a_list, 0, len(a_list) - 1))))
[0, 100, 300, 600]
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • 1
    `accumulate(chain([0], islice(a_list, 0, -1))` would avoid creation of two temporary lists, for people who care about that kind of things. BTW ignoring the last element of the list seems like a mistake in the question, for which I've asked the submitter for clarification. – user4815162342 May 24 '14 at 10:42
  • @user4815162342, Thank you for comment. I updated the answer according to you. BTW, `itertools.islice` does not accept negative index. – falsetru May 24 '14 at 10:46
  • Thanks for the update. The price for increased efficiency is (as is frequently the case) less readable code. But I still believe the OP didn't really intend to ignore the last element of the input list. :) – user4815162342 May 24 '14 at 10:48