adjacent differences with a list comprehension

Jeremy Fincher tweedgeezer at hotmail.com
Mon Mar 24 21:00:46 EST 2003


pschmidt at omnimn.com (Phil Schmidt) wrote in message news:<69413f9.0303241331.62f0295f at posting.google.com>...
> 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]

First, define a "window" iterator (useful for many other things in
addition to this):

def window(L, size):
    for i in xrange(len(L) - size + 1):
        yield L[i:i+size]

The it's simple:

[y - x for (x, y) in window(L, 2)]

Jeremy




More information about the Python-list mailing list