Reputation:
I have a list:
a = [0, 4, 10, 100]
I want to calculate difference between consecutive elements in list. I do this:
[x - a[i-1] for i, x in enumerate(a)]
But it brings me this result:
[-100, 4, 6, 90]
As you see first element is -100, but I want to keep first element unchanged, when I make such transformation to get this [0, 4, 6, 90]
. How to do that?
Upvotes: 2
Views: 433
Reputation: 1028
If you don't mind importing numpy, this will do it very quickly for long lists:
import numpy as np
a = [0, 4, 10, 100]
np.diff(a, prepend=0).tolist()
Upvotes: 0
Reputation: 4427
A variation using zip
is to just add a leading 0, since item - 0
will be 0.
x = [0, 4, 10, 100]
assert [b - a for a, b in zip([0] + x, x)] == [0, 4, 6, 90]
If you are dealing with massive lists, running this in a loop, and care about performance, then you might not want the overhead of appending all of a
to a new list, and can use another solution or itertools.chain([0], a)
.
Upvotes: 1
Reputation: 76
As Timur mentioned, a list comprehension will provide the most compact solution.
With zip we don't need conditionals (but we lose the first element):
a = [0, 4, 10, 100]
b = [a[0]] + [b-a for a, b in zip(a, a[1:])]
# [0, 4, 6, 90]
Upvotes: 1
Reputation: 12347
Use list comprehension with a conditional expression:
a = [0, 4, 10, 100]
b = [a[i] - a[i-1] if i > 0 else a[i] for i in range(len(a))]
print(b)
# [0, 4, 6, 90]
Upvotes: 1