adjacent differences with a list comprehension

John Machin sjmachin at lexicon.net
Mon Mar 24 17:28:32 EST 2003


On 24 Mar 2003 13:31:16 -0800, pschmidt at omnimn.com (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!

>>> L = [2, 5, 8, 3, 9, 1]
>>> [L[i+1]-L[i] for i in xrange(len(L)-1)]
[3, 3, -5, 6, -8]
>>>

Depends on your definitions of "easily" and "elegantly" :-)




More information about the Python-list mailing list