Read other items in a python list while iterating through it

Question:

I use code like this to iterate through a list when I also need the next item in the list:

values = [1, 3, 6, 7 ,9]
diffs = []
for i in range(len(values)):
    try: diffs.append(values[i+1] - values[i])
    except: pass

print diffs

How can I simplify this?

gives:

[2, 3, 1, 2]
Asked By: bluegray

||

Answers:

You could use

for pos, item in enumerate(values):
    try:
        diffs.append(values[pos+1] - item)
    except IndexError:
        pass

although in your case (since you’re just looking for the next value), you could also simply use

for item,nextitem in zip(values, values[1:]):
    diffs.append(nextitem-item)

which can also be expressed as a list comprehension:

diffs = [nextitem-item for item,nextitem in zip(values, values[1:])]
Answered By: Tim Pietzcker
>>> values = range(10)
>>> values
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> zip(values[0:],values[1:])
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9)]
Answered By: Katriel
for i, j in zip(values, values[1:]):
     j - i
Answered By: SilentGhost
diff = [values[i+1] - values[i] for i in range(len(values)-1)]
Answered By: Sven Marnach

what about with the aid of pairwise recipe from itertools document

from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)
def main():
    values = [1, 3, 6, 7 ,9]
    diffs = [post - prior for prior, post in pairwise(values)]
    print diffs


if __name__ == "__main__":
    main()

output
[2, 3, 1, 2]

Answered By: sunqiang
[y - x for x,y in zip(L,L[1:])]
Answered By: ceth
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.