How to keep first element in list unchanged when I calculate difference between consecutive elements in list?

Viewed 226

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?

4 Answers

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]

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).

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()
Related