Eddy Pronk
Eddy Pronk

Reputation: 6695

Subtracting the current and previous item in a list

It is very common to write a loop and remember the previous.

I want a generator that does that for me. Something like:

import operator

def foo(it):
    it = iter(it)
    f = it.next()
    for s in it:
        yield f, s
        f = s

Now subtract pair-wise.

L = [0, 3, 4, 10, 2, 3]

print list(foo(L))
print [x[1] - x[0] for x in foo(L)]
print map(lambda x: -operator.sub(*x), foo(L)) # SAME

Outputs:

[(0, 3), (3, 4), (4, 10), (10, 2), (2, 3)]
[3, 1, 6, -8, 1]
[3, 1, 6, -8, 1]

Upvotes: 11

Views: 15438

Answers (3)

ceth
ceth

Reputation: 45295

[y - x for x,y in zip(L,L[1:])]

Upvotes: 49

pillmuncher
pillmuncher

Reputation: 10162

Recipe from iterools:

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)

and then:

>>> L = [0, 3, 4, 10, 2, 3]
>>> [b - a for a, b in pairwise(L)]
[3, 1, 6, -8, 1]

[EDIT]

Also, this works (Python < 3):

>>> map(lambda(a, b):b - a, pairwise(L))

Upvotes: 4

Madison Caldwell
Madison Caldwell

Reputation: 862

l = [(0,3), (3,4), (4,10), (10,2), (2,3)]
print [(y-x) for (x,y) in l]

Outputs: [3, 1, 6, -8, 1]

Upvotes: 4

Related Questions