Skip to content Skip to sidebar Skip to footer

Python For Loop, How To Find Next Value(object)?

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 entry in entries: first

Solution 1:

It should be noted that none of these solutions work for generators. For that see Glenn Maynards superior solution.

use zip for small lists:

 for current, last in zip(entries[1:], entries):
     diff = current - last

This makes a copy of the list (and a list of tuples from both copies of the list) so it's good to use itertools for handling larger lists

import itertools as it

items = it.izip(it.islice(entries, 1, None), entries)
for current, last in items:
    diff = current - last

This will avoid both making a copy of the list and making a list of tuples.

Another way to do it without making a copy is

entry_iter = iter(entries)
entry_iter.next() # Throw away the first version
for i, entry in enumerate(entry_iter):
    diff = entry - entries[i]

And yet another way is:

for i in xrange(len(entries) - 1):
    diff = entries[i+1] - entries[i]

This creates an iterator that indexes entries and advances it by one. It then uses enumerate to get an indice with the item. The indice starts at 0 and so points to the previous element because we the loop one item in.

Also, as Tyler pointed out in the comment, a loop might be overkill for such a simple problem if you just want to iterate over the differences.

diffs = (current - last for current, last in 
         it.izip(it.islice(entries, 1, None), entries))

Solution 2:

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.


Solution 3:

i don't know exactly what are you looking but maybe this can help :

first = entries[0]
for entry in entries[1:]:
    last = entry       
    diff = last - first 
    first = entry

Solution 4:

very simply, using enumerate, no fancy stuff

>>> entries=[10,20,30,40]
>>> for n,i in enumerate(entries):
...     try:
...        print entries[n+1] - i
...     except IndexError:
...        print entries[-1]
...
10
10
10
40

Post a Comment for "Python For Loop, How To Find Next Value(object)?"