0

I'm attempting to loop through a list and if list[index] == previous list[index] so == list[index-1], the script should delete both of those elements.

But I'm getting a weird Index Error which in my opinion shouldn't happen:

Here is my code

m = list(input())

for i in range(1, len(m)):
    if m[i] == m[i-1]:
        del m[i]
        del m[i-1]

But it's crashing with the following error

line 4, in <module>
    if m[i] == m[i-1]:
IndexError: list index out of range

Thank you in advance for helping me.

Beni
  • 31
  • 2
  • 3
    You shouldn't be modifying a list as you iterate through it. By shortening your list, you will eventually be accessing indices that do not exist anymore. – user3483203 Jul 28 '21 at 16:24

0 Answers0