adjacent differences with a list comprehension

Greg Ewing (using me at
Tue Mar 25 00:25:08 CET 2003

Sean Ross wrote:
> This will do what you're looking for:
> def adjacentdiffs(seq):
>     return [ x - y  for x, y in zip (seq[1:], seq[:-1]) ]

While that works, I think it obfuscates what's being
done rather more than necessary.

I would suggest:

   [seq[i+1] - seq[i] for i in xrange(len(seq) - 1)]

It's a bit more efficient to boot, since it avoids
constructing an intermediate list of tuples.

Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand

More information about the Python-list mailing list