0

Beginner question: I am trying to evaluate whether two values in a row match.

a = ['sl','sl','cr','cl']

This is my current code:

while (j+1) < len(a):
    if a[j] == a[j+1]:
        num = num + 1
    else: 
        num = num

However, when I do it this way it doesn't count the first value in the list - this is due to (j+1), however, if I remove it, get an error telling me my index is out of range - any advice would be appreciated.

B C
  • 318
  • 3
  • 16

1 Answers1

1

There are a few things you should improve in your code. First, loop over enumerate(list) to easily compare items in the list. Second, IndexError can be used to quit the loop after the last index is reached. Here an --easy-to-read-- example.

for i,item in enumerate(a):
    try:
        if item = a[i+1]:
            print(item, 'and', a[i+1], 'are the same')
            #increment your counter here
    except IndexError:
        break
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • You could always loop over `enumerate(a[:-1])` to avoid the `IndexErrror` in the first place. Or `a[1:]` and use the previous value instead of the next... (also you might want to use `==` in the `if`) – Baldrickk Jun 07 '17 at 10:17
  • @Baldrickk Indeed, that is a good suggestion for a beginner. I prefer my way, I find it more explicit, but thanks! – alec_djinn Jun 07 '17 at 10:20