Home > Back-end >  How to subtract the value in a list with preserving value with preserving the first index value
How to subtract the value in a list with preserving value with preserving the first index value

Time:02-24

I have a list of values. Now I want to subtract the values in list with the previous values while ignoring the subtraction for the first index value. Although I did it, It's not appending the first index value into the newly created list. How do I append the first index value into the list?

list1 = [269.76666, 284.1666, 309.45, 357.21666666666664, 393.8833333333333, 443.81666666666666]

diffs = [y - x for x, y in zip(list1 , list1 [1:])]

Output displayed:-
[14.399940000000015,
 25.283399999999972,
 47.76666666666665,
 36.666666666666686,
 49.93333333333334]

Execpted output:-
[269.76666,
14.399940000000015,
 25.283399999999972,
 47.76666666666665,
 36.666666666666686,
 49.93333333333334]

CodePudding user response:

Since your code selects two values at a time, it doesn't add the 1st value, i.e. it chooses the 1st-2nd, 2nd-3rd and so on.
So, you can either add the 1st value at the start of diffs or add a zero in the original list. Code:

list1 = [269.76666, 284.1666, 309.45, 357.21666666666664, 393.8833333333333, 443.81666666666666]
list1 = [0] list1
diffs = [y - x for x, y in zip(list1 , list1 [1:])]
print(diffs)

Or

list1 = [269.76666, 284.1666, 309.45, 357.21666666666664, 393.8833333333333, 443.81666666666666]
diffs = [y - x for x, y in zip(list1 , list1 [1:])]
diffs = [li]
print(diffs)

CodePudding user response:

You are almost there -

first, *rest = list1
diffs = zip(list1[:-1], rest)
final = [first]   [y - x for x, y in diffs]

In the above answer, the first and rest split is only for helping readability, you can do away with it too by using the indices directly

  • Related