0

I have the following list:

list_1 = [2.03898103, 2.23708741, 1.68221573, 1.12352885, 0.56227805]

And I want to add the numbers to the first number into the new list like this:

list_2 = []
list_2[0] = list_1[0]
list_2[1] = list_1[0] + list_1[1]
list_2[2] = list_1[0] + list_1[1] + list_1[2]
list_2[3] = list_1[0] + list_1[1] + list_1[2] + list_1[3]
list_2[4] = list_1[0] + list_1[1] + list_1[2] + list_1[3] + list_1[4]

How can I make this with a for loop or something more practical?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zaid Khalil
  • 13
  • 1
  • 6

5 Answers5

2

Just in case you want a short answer, you can also use generators:

list_2 = [sum(list_1[:(i+1)]) for i in range(len(list_1))]
1

You can use itertools.accumulate:

from itertools import accumulate

list_1 = [2.03898103, 2.23708741, 1.68221573, 1.12352885, 0.56227805]
list_2 = list(accumulate(list_1))
print(list_2)

Prints:

[2.03898103, 4.2760684399999995, 5.95828417, 7.08181302, 7.64409107]
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
1
list_1 = [2.03898103, 2.23708741, 1.68221573, 1.12352885, 0.56227805]
list_2 = []
j = 0.
for i in range(0,len(list_1)):
    j = j + list_1[i]
    list_2.append(j)
print(list_2)
Alex
  • 11
  • 2
1

You've tagged as NumPy in your question, so just use numpy.cumsum:

>>> import numpy as np
>>> list_1 = np.array([2.03898103, 2.23708741, 1.68221573, 1.12352885, 0.56227805])
>>> np.cumsum(list_1)
array([2.03898103, 4.27606844, 5.95828417, 7.08181302, 7.64409107])
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Woodford
  • 3,746
  • 1
  • 15
  • 29
1

You can use multiple for loops.

list_1 = [2.03898103, 2.23708741, 1.68221573, 1.12352885, 
0.56227805]
list_2 = []

for i in range(0, 4):
     for j in range(0, i):
          list_2[i] += list_1[j]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131