adjacent differences with a list comprehension

Mario A. Botto mariobot at yahoo.com
Wed Apr 2 01:25:56 CEST 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]
> 
> I don't see how I can do this (easily/elegantly) with list
> comprehensions.
> 
> Any suggestions? Thanks!

Hi.
How about this? 
If, say, L1 = [a1, a2, a3], L2 = [b1, b2, b3, b4, b5], then 
zip(L1, L2) = [(a1,b1), (a2,b2), (a3, b3)]. Hence, 
[a - b for (a,b) in zip(L1, L2)] = [a1-b1, a2-b2, a3-b3]

This solves your problem if you set L1 = L, L2 = L[1:]. That is,

Ld = [a - b for (a,b) in zip(L[1:], L)]
print 'Ld: ', Ld
>> Ld:  [3, 3, -5, 6, -8]
 
Cheers.




More information about the Python-list mailing list