2

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.

Dominique
  • 16,450
  • 15
  • 56
  • 112
Ali Akhtari
  • 1,211
  • 2
  • 21
  • 42
  • 2
    *[...] if my list length is less than 3* then just use `len()` function. See https://stackoverflow.com/questions/1712227/how-to-get-the-number-of-elements-in-a-list-in-python – Mazdak Jul 06 '18 at 10:38
  • 1
    i try this, but i faced same error – Ali Akhtari Jul 06 '18 at 10:40
  • 1
    The reason that you're getting `IndexError` is because you're trying to use indexes that are not available in your list. You should find out where are you doing such thing and correct it. – Mazdak Jul 06 '18 at 10:42
  • 2
    `range(0, len(a1)-2)` is only evaluated once, but you change `len` of the list with `remove`. [How does a for loop evaluate its argument](//stackoverflow.com/a/35439647) – 001 Jul 06 '18 at 10:46
  • 2
    @JohnnyMopp Thank You, my Problem is solve. – Ali Akhtari Jul 06 '18 at 10:49

1 Answers1

0

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.

Dominique
  • 16,450
  • 15
  • 56
  • 112