adjacent differences with a list comprehension

Greg Ewing (using news.cis.dfn.de) me at privacy.net
Mon Mar 24 18:25:08 EST 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
http://www.cosc.canterbury.ac.nz/~greg





More information about the Python-list mailing list