2

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?

smci
  • 32,567
  • 20
  • 113
  • 146
Jochen
  • 155
  • 1
  • 3
  • 15
  • You have to tell us what `do_something()` is, quite often in Python you don't want a loop, you want a list comprehension. Especially if your code is building a new list/dict/etc. – smci Apr 20 '20 at 12:24

2 Answers2

3

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.

Chad S.
  • 6,252
  • 15
  • 25
  • upvote for first suggestion. No additional package and no definition of helper function! thx – Jochen Sep 01 '15 at 09:55
3

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)
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • upvote for first solution with iter tools, but what is the advantage over polpak's first solution? – Jochen Sep 01 '15 at 10:42