HI, I\'m trying to use for loop to find the difference between every two object by minus each other. So, how can I find the next value in a for loop?
for ent
zip works for lists, but for the general case:
def pairs(it):
it = iter(it)
prev = next(it)
for v in it:
yield prev, v
prev = v
a = [1,2,3,4,5]
for prev, cur in pairs(a):
print cur - prev
import itertools as it
for prev, cur in pairs(it.cycle([1,2,3,4])):
print cur - prev
This works efficiently for large containers, and more importantly, it works for iterators:
for prev, cur in pairs(open("/usr/share/dict/words").xreadlines()):
print cur, prev,
Edit: I changed the generator to omit the first value with no previous value, since that fits the original question better ("finding differences between adjacent pairs"), and I added an example case showing that it works for an infinitely-repeating iterator.