I have a list of integers:
x = [3, 5, 2, 7]
And I want to create a new list where the nth
element is the sum of elements in x
from 0
to n-1
.
This would result in:
y = [0, 3, 8, 10]
How can I do this with list comprehension, without running a loop?
How about without a loop and without a list comprehension? Sadly only Python 3:
>>> x = [3, 5, 2, 7]
>>> from itertools import accumulate
>>> [0] + list(accumulate(x[:-1]))
[0, 3, 8, 10]
Update: Here's an O(n) list comprehension solution:
>>> s = [0]
>>> [s.append(s[0]+n) or s.pop(0) for n in x]
[0, 3, 8, 10]
But I only wanted to show that that's possible without too much effort. I think accumulate
or a for loop are much better.