Difference between consecutive elements in list [duplicate]
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
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)
Use it like this:
>>> a = [0, 4, 10, 100]
>>> [y-x for x,y in pairwise(a)]
[4, 6, 90]
[x - a[i-1] if i else None for i, x in enumerate(a)][1:]