Jochen
Jochen

Reputation: 155

How to iterate/loop over a list and reference previous (n-1) element?

I need to iterate over a list and compare the current element and the previous element. I see two simple options.

1) Use enumerate and indexing to access items

for index, element in enumerate(some_list[1:]):
    if element > some_list[index]: 
        do_something()

2) Use zip() on successive pairs of items

for i,j in zip(some_list[:-1], some_list[1:]):
    if j > i:
        do_something()

3) itertools

I personally don't like nosklo's answer from here, with helper functions from itertools

So what is the way to go, in Python 3?

Upvotes: 2

Views: 3333

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You can use iter which avoids the need to index or slice:

it = iter(some_list)
prev = next(it)
for ele in it:
     if prev > ele:
         # do something
    prev = ele

There is also the pairwise recipe in itertools which uses tee:

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

for a,b in pairwise(some_list):
    print(a,b)

Upvotes: 3

Chad S.
Chad S.

Reputation: 6633

The zip method is probably the most commonly used, but an alternative (which may be more readable) would be:

prev = None
for cur in some_list:
   if (prev is not None) and (prev > cur):
       do_something()
   prev = cur

This will obviously not work if None can occur somewhere in some_list, but otherwise it does what you want.

Another version could be a variation on the enumerate method:

for prev_index, cur_item in enumerate(somelist[1:]):
    if somelist[prev_index] > cur_item:
        do_something()

Just be sure not to modify somelist in the loop or the results will be unpredictable.

Upvotes: 3

Related Questions