I got error saying IndexError: list index out of range. how do I fix this?

Viewed 404
   res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]      

   while not i>(len(res)-1):
        if res[i]==res[i+1]:
            answer+=2
            i+=2
        else:
            i+=1

The variable "answer" is supposed to count duplicated numbers that are placed next to each other. For some reason, I get the error saying IndexError: list index out of range. How do I fix this?

3 Answers

Let's start off by simplifying the code a bit. The condition

not i > (len(res) - 1)

can be converted to

i <= (len(res) - 1)

which can be further converted to

i < len(res)

This means that i will always be less than the length of res, which makes it a valid index. However, within the body of the while, on this line:

if res[i]==res[i+1]:
    ...

we indexed res with i + 1, which for the last possible value of i will be an invalid index (i + 1 will be equal to len(res)). We have to ensure that not only i is less than len(res), but also that i + 1 is less than len(res), giving us this fixed version of the code:

while i + 1 < len(res):
    if res[i] == res[i + 1]:
        answer += 2
        i += 2
    else:
        i += 1

Running this code on your example res gives an answer of 4, which looks right.

How about giving it this approach?

res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]
answer = 0
start = 0
while start < len(res):
    if start + 1 < len(res):
        if res[start] == res[start + 1]:
            answer += 1
            start += 2
        else:
            start += 1
    else:
        start += 1
print(answer)

If you you want to count overlapping pairs also, you can use this approach:

res = [3, 1, 1, 5, 2, 4, 2, 4, 2, 4, 3, 1, 1, 5, 3]
for i, j in zip(res, res[1:]):
    if i == j:
        amount += 2

Another approach could be:

for i, _ in enumerate(res):
    if i < len(res) - 1 and res[i] == res[i+1]:
        amount += 2
Related