Python: Finding differences between elements of a list

Python: Finding differences between elements of a list

>>> 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 youre doing numerical work, you might want to consider numpy. Using numpy, the answer is:

v = numpy.diff(t)

Python: Finding differences between elements of a list

If you dont want to use numpy nor zip, you can use the following solution:

>>> t = [1, 3, 6]
>>> v = [t[i+1]-t[i] for i in range(len(t)-1)]
>>> v
[2, 3]

Leave a Reply

Your email address will not be published. Required fields are marked *