'IndexError: list index out of range in for loop
I write a code in python but I faced this error :
if a1[i] == a1[i+1] == a1[i+2]:
IndexError: list index out of range
I write an if condition that if my list length is less than 3, break the for, but it does not work.
My Code :
numb = int(input())
a1 = []
a2 = []
a = 0
a1 = [int(i) for i in input().split()]
for i in range(0, numb):
a2.append("empty")
for i in range(0, len(a1)-2):
if len(a1) < 3:
break
else:
if a1[i] == a1[i+1] == a1[i+2]:
a = a + 1
a2[i] = a
a2[i+1] = a
a2[i+2] = a
a1.remove(a1[i+2])
a1.remove(a1[i+1])
a1.remove(a1[i])
Why do I face this error?
Is it because my if-condition does not work?
In Addition, I'm sorry for writing mistakes in my question.
Solution 1:[1]
Your loop goes from 0 to len(a1)-2, while you should only go to len(a1)-3:
When you are working with i, let i go from 0 to len(a1)-1.
When you are working with i and i+1, let i go from 0 to len(a1)-2.
When you are working with i, i+1 and i+2 let i go from 0 to len(a1)-3.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dominique |
