0

I have a list of values like this one:

L = [2, 5, 6, 8, 10, 13]

I want to calculate the difference between the first two values and store it into a list using the list indexes. Then, calculate the difference between the second and the third and so on...

I tried a loop like this without success:

[(L[i+1] - L[i]) for i in L]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
  • Duplicate: https://stackoverflow.com/questions/2400840/python-finding-differences-between-elements-of-a-list – Sunil Mar 01 '21 at 12:22

1 Answers1

0

In your loop, i holds the value, not the index, iterate over range(len(L)) to get the indices (actually range(len(L) - 1) since you're getting the next value):

>>> [(L[i + 1] - L[i]) for i in range(len(L) - 1)]
[3, 1, 2, 2, 3]

In this case, zip can come-in handy too (iterating over values here):

>>> [y - x for x, y in zip(L, L[1:])]
[3, 1, 2, 2, 3]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55