Note that Python's official style-guide, PEP8, recommends using lower_case
names for variables, so I changed all your L
s to l
and all your new_L
to new_l
.
l = [4, 2, 1, 3]
You should keep track of the cumulative sum in a variable. This way you avoid having to test whether the new_l
already has an element in it:
def add_one_by_one(l):
new_l = []
cumsum = 0
for elt in l:
cumsum += elt
new_l.append(cumsum)
return new_l
As an alternative, you could use a generator to avoid having to build the list inside the function (if you are just going to iterate over it later, this is the most memory-efficient way):
def add_one_by_one_gen(l):
cumsum = 0
for elt in l:
cumsum += elt
yield cumsum
new_l = list(add_one_by_one_gen(l))
# This takes basically no additional memory (only one float/int):
for x in add_one_by_one_gen(l):
print x
(Replace print x
with print(x)
in Python 3.x.)
Probably the fastest way to do it would be using the numpy
function cumsum
:
import numpy as np
new_l = np.cumsum(l)