tags:

views:

101

answers:

3

Given a list of numbers how to find differences between every (i)-th and (i+1)-th of its elements? Should one better use lambda or maybe lists comprehension?

Example: Given a list t=[1,3,6,...] it is to find a list v=[2,3,...] because 3-1=2, 6-3=3, etc.

+8  A: 
>>> t
[1, 3, 6]
>>> [j-i for i, j in zip(t[:-1], t[1:])]  # or use itertools.izip in py2k
[2, 3]
SilentGhost
+1  A: 

Ok. I think I found the proper solution:

v = [x[1]-x[0] for x in zip(t[1:],t[:-1])]
psihodelia
+1  A: 

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)
ianalis