Python: Finding differences between elements of a list
Given a list of numbers, how does one find differences between every (i
)-th elements and its (i+1
)-th?
Is it better to use a lambda
expression or maybe a list comprehension?
For example:
Given a list t=[1,3,6,...]
, the goal is to find a list v=[2,3,...]
because 3-1=2
, 6-3=3
, etc.
>>> t
[1, 3, 6]
>>> [j-i for i, j in zip(t[:-1], t[1:])] # or use itertools.izip in py2k
[2, 3]
The other answers are correct but if you're doing numerical work, you might want to consider numpy. Using numpy, the answer is:
v = numpy.diff(t)