0

I am new to python, and I did do a search to try and find someone with a similar question and could not find anything, so here it goes!

I am trying to apply percentage changes to a list. So for example if we have:

list = [1,2,3,4,5,6] 

I want to iterate through the list but using the formula (current value - previous value) / previous value ) * 100

In the provided list above it would be:

((2-1)/1)*100 and then ((3-2)/2)*100 etc. And then append to new list [100, 50, etc]

So far I have:

for i in equity:
    equity_percentages.append(((i - equity[0])/equity[0])*100)

Which obviously only subtracts the first value in the list and then divides by that value as well. What I want to do is iterate through that list sequentially using the above mentioned formula.

John
  • 29
  • 5
  • I know this has been answered already, but here's a cool little trick you can use to perform this task while taking advantages of Python's features, like slicing and the `zip` function that iterates through sequences side-by-side: `mylist = [1,2,3,4,5,6]; for i, j in zip(mylist, mylist[1:]): print((j - i) / i * 100)` – jfaccioni Sep 07 '19 at 00:10

1 Answers1

0
equity = [1,2,3,4,5,6]
equity_percentages = []

i = 1
while i < len(equity):
    equity_percentages.append(((equity[i] - equity[i-1])/equity[i-1])*100)
    i += 1

print(equity_percentages)
Diogo Rocha
  • 9,759
  • 4
  • 48
  • 52
  • Thank you! Just curious, why am i not able to do the same thing with with a for loop? I tried something very simliar indexing equity[i-1] and was thrown with some errors. "index out of range" – John Sep 07 '19 at 00:02