Search code examples
pythonlistindex-error

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


   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?


Solution

  • 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)