adjacent differences with a list comprehension

Sean Ross sross at connectmail.carleton.ca
Mon Mar 24 17:02:44 EST 2003


This will do what you're looking for:

def adjacentdiffs(seq):
    return [ x - y  for x, y in zip (seq[1:], seq[:-1]) ]

Sean



"Phil Schmidt" <pschmidt at omnimn.com> 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]
>
> I don't see how I can do this (easily/elegantly) with list
> comprehensions.
>
> Any suggestions? Thanks!






More information about the Python-list mailing list