2

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?

  • Anything wrong with just `result[0] += a[-1]`? – Brian61354270 Feb 16 '21 at 21:43
  • You use a completely different rule for the first item. So, you might just define your output as `[first_item]` + the list of differences from one item to the next, for which there a many solutions, like in https://stackoverflow.com/questions/2400840/python-finding-differences-between-elements-of-a-list – Thierry Lathuille Feb 16 '21 at 21:44
  • You have only three differences in your series. Why do you want four elements in the result? It's not that you "keep the first element unchanged" -- the difference process does not *change* any element; it returns a new sequence of values. – Prune Feb 16 '21 at 21:58

4 Answers4

1

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]
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
1

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]
Woody
  • 76
  • 3
1

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

Cireo
  • 4,197
  • 1
  • 19
  • 24
0

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()
Durtal
  • 1,063
  • 3
  • 11