-1

Imagine I have a list of values and I want to compare current value with previous value of the list using for loop. How to do that?

ShoeMaker
  • 149
  • 1
  • 2
  • 9
  • 1
    you just use the previous index...? if the current index is `i`, the previous element is at `i-1` – Chase Jun 22 '20 at 12:17
  • Does this answer your question? [Python loop that also accesses previous and next values](https://stackoverflow.com/questions/1011938/python-loop-that-also-accesses-previous-and-next-values) – DarrylG Jun 22 '20 at 12:40

2 Answers2

1

Instead of doing your for loop like this (which is the preferred way)

for element in list:
    do_something()

You can do this:

for i in range(len(list)):
    element = list[i]
    previous_element = list[i-1]
    do_something()

Pay attention that in the first iteration, i will be 0 so list[i-1] will give the last element of the list, not the previous, since there is no previous.

debsim
  • 582
  • 4
  • 19
0

In case you're using for...in variable and hence do not have the indexes, enumerate is the pythonic way to achieve what you want.

for index, current_item in enumerate(variable):
    prev = variable[index - 1] if index > 0 else None
    # Use prev and current_item here
Chase
  • 5,315
  • 2
  • 15
  • 41