Calculate differences between elements of a sequence in Python
I often encounter the need to calculate the (finite) differences between elements of a sequence, e.g., to calculate the duration between points in a time-series.
The calculation is simple, for the sequence [a,b,c,d]
the difference between the elements are [b-a,c-b,d-c]
.
Hence, for the sequence [1,2,3,5,6,9]
, the differences between the elements are: [1,1,2,1,3]
.
The function is built-in to most high-level languages used for technical computing, such as Matlab and Julia.
To the best of my knowledge, Python doesn't have a built in way to perform this calculation.
Here's the function I've created, implementing the diff
algorithm in Python, using tee from the built-in itertools module:
from itertools import tee
def diff(s):
"""Diff elements of a sequence:
s -> s1 - s0, s2 - s1, s3 - s2, ...
"""
a, b = tee(s)
next(b, None)
return (j - i for i, j in zip(a, b))
This works fine, but maybe there is a more compact, and elegant way to do it.