adjacent differences with a list comprehension

Fernando Perez fperez528 at yahoo.com
Mon Mar 24 23:46:51 CET 2003


Phil Schmidt wrote:

> Given a list of numbers, such as:
> 
> L = [2, 5, 8, 3, 9, 1]
> 
> I want to generate a list containing the differences between adjacent
> elements, i.e.,
> 
> Ld = [3, 3, -5, 6, -8]
> 
> I don't see how I can do this (easily/elegantly) with list
> comprehensions.
> 
> Any suggestions? Thanks!

Numeric provides the simplest possible way of writing this:

In [1]: L = array([2, 5, 8, 3, 9, 1])

In [2]: L[1:]-L[:-1]
Out[2]: array([ 3,  3, -5,  6, -8])

Note that in the above, the data is NOT copied when you do L[1:], so even if L 
is a multi-megabyte array, you won't incurr a copy penalty.  The semantics of 
Numeric slicing is different from that of python lists, for very good reasons. 
And the loop is done in C, so it's extremely fast.

Cheers,

f.




More information about the Python-list mailing list