Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between consecutive elements in list [duplicate]

Tags:

python

list

Possible Duplicate:
Python - Differences between elements of a list

I have a list and I want to find difference between consecutive elements:

a = [0, 4, 10, 100] find_diff(a) >>> [4,6,90] 

How would you code find_diff() function? I can code this with "for" iterator but I am sure there are very simple ways to do it with a simple one liner.

like image 783
gok Avatar asked Mar 15 '11 15:03

gok


2 Answers

You could utilize enumerate, zip and list comprehensions:

>>> a = [0, 4, 10, 100]  # basic enumerate without condition: >>> [x - a[i - 1] for i, x in enumerate(a)][1:] [4, 6, 90]  # enumerate with conditional inside the list comprehension: >>> [x - a[i - 1] for i, x in enumerate(a) if i > 0] [4, 6, 90]  # the zip version seems more concise and elegant: >>> [t - s for s, t in zip(a, a[1:])] [4, 6, 90] 

Performance-wise, there seems to be not too much variance:

In [5]: %timeit [x - a[i - 1] for i, x in enumerate(a)][1:] 1000000 loops, best of 3: 1.34 µs per loop  In [6]: %timeit [x - a[i - 1] for i, x in enumerate(a) if i > 0] 1000000 loops, best of 3: 1.11 µs per loop  In [7]: %timeit [t - s for s, t in zip(a, a[1:])] 1000000 loops, best of 3: 1.1 µs per loop 
like image 83
miku Avatar answered Oct 08 '22 15:10

miku


Use the recipe for pairwise from the itertools documentation:

from itertools import izip, tee def pairwise(iterable):     "s -> (s0,s1), (s1,s2), (s2, s3), ..."     a, b = tee(iterable)     next(b, None)     return izip(a, b) 

Use it like this:

>>> a = [0, 4, 10, 100] >>> [y-x for x,y in pairwise(a)] [4, 6, 90] 
like image 21
Steven Rumbalski Avatar answered Oct 08 '22 16:10

Steven Rumbalski