0

If there is a list A = [1, 4, 10] I want to change the list A into A = [1, 3, 6] where:

  • 1 would stay the same,
  • 4 would be 4 - 1 = 3,
  • 10 would be 10 - 4 = 6

How can I do this? So far, I have done

A = [1, 4, 10]
for i, num in enumerate(A):
    if i == 0:
        A[i] = A[0]
    else:
        A[i] = A[i] - A[i-1]
print(A)

but the printed A would be [1, 3, 7]

Anwarvic
  • 12,156
  • 4
  • 49
  • 69
Dylan
  • 103
  • 6

2 Answers2

0

Use zip:

A = [1, 4, 10]
A = [A[0]] + [x2 - x1 for (x1, x2) in zip(A, A[1:])]

A:

[1, 3, 6]
Pygirl
  • 12,969
  • 5
  • 30
  • 43
0

Try this:

A = [1, 4, 10]

for i, num in enumerate(A[1:]):
    idx = len(A)-1 - i
    A[idx] = A[idx] - A[idx-1]
print(A)
# [1, 3, 6]
Anwarvic
  • 12,156
  • 4
  • 49
  • 69