adjacent differences with a list comprehension
Alex Martelli
aleax at aleax.it
Mon Mar 24 17:47:44 EST 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!
I see you've already received two excellent suggestions based on
zip, so here's the alternative based on indices instead:
[ L[i+1]-L[i] for i in range(len(L)-1) ]
Alex
More information about the Python-list
mailing list