0

I'm new to python and this may be a simple one line or one character answer but I can't seem to wrap my head around it. I have a list I want to iterate through and check if the element in the index after the current index is the same and delete it if it is.

while i < len(list):
    if list[i] == list[i+1]:
        del list[i];
    i+=1;

I know the problem is coming from "if list[i] == list[i+1]:" when I get to end of the list "list[i+1]" will be out of range of the index. The problem is that I don't know how to stop the code when it gets to that point where it goes out of range

1 Answers1

0

Firstly, list is the built-in function of python, so you should never use it for the name of your variables.

And to your problems itself. The fix for your error is simple:

while i < (len(_list) - 1):
    if _list[i] == _list[i+1]:
        del _list[i]
    i+=1;

The reason for the IndexError is that at the last iteration i is already the last index and you are trying to get the element at the i+1 position.

Dmitry Yantsen
  • 1,145
  • 11
  • 24