Difference between consecutive elements in list

Question:

Possible Duplicate:
Python – Differences between elements of a list

I have a list and I want to find difference between consecutive elements:

a = [0, 4, 10, 100]
find_diff(a)
>>> [4,6,90]

How would you code find_diff() function? I can code this with “for” iterator but I am sure there are very simple ways to do it with a simple one liner.

Asked By: gok

||

Answers:

You could utilize enumerate, zip and list comprehensions:

>>> a = [0, 4, 10, 100]

# basic enumerate without condition:
>>> [x - a[i - 1] for i, x in enumerate(a)][1:]
[4, 6, 90]

# enumerate with conditional inside the list comprehension:
>>> [x - a[i - 1] for i, x in enumerate(a) if i > 0]
[4, 6, 90]

# the zip version seems more concise and elegant:
>>> [t - s for s, t in zip(a, a[1:])]
[4, 6, 90]

Performance-wise, there seems to be not too much variance:

In [5]: %timeit [x - a[i - 1] for i, x in enumerate(a)][1:]
1000000 loops, best of 3: 1.34 µs per loop

In [6]: %timeit [x - a[i - 1] for i, x in enumerate(a) if i > 0]
1000000 loops, best of 3: 1.11 µs per loop

In [7]: %timeit [t - s for s, t in zip(a, a[1:])]
1000000 loops, best of 3: 1.1 µs per loop
Answered By: miku

Use itertools.pairwise (Python 3.10+):

>>> from itertools import pairwise
>>> a = [0, 4, 10, 100]
>>> [y - x for x, y in pairwise(a)]
[4, 6, 90]

For Python 3.9 and older you can use the recipe for pairwise from the itertools documentation:

from itertools import izip, tee
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)
Answered By: Steven Rumbalski
[x - a[i-1] if i else None for i, x in enumerate(a)][1:]
Answered By: kindall
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.