-2

IndexError: list index out of range

I am looking for doubled strings in a list and want to remove if there is a repetition. So I use if statement for checking if a element in a list equals to the next and then remove if ture. But unexpectedly when I use del list[i] code returns error.

for i in range(len(formatted_text)-1):
  if(formatted_text[i] == formatted_text[i+1]):
    # formatted_text[i+1] = ''
    print(len(formatted_text)) # it is equal to 11
    print(i)                   # the repetition is at 4 and 5 element 
    del formatted_text[i]      # removal instruction

I expect it to execute normally, don't know where the problem is. When i check it without loop it works normally.

EDIT: I managed to solve this problem. Unfortunately (len(formatted_text)-2, 0 ,-1) doesn't work if the repetition is at the beginning of a list. Here is the code that work's just fine and is friendly:

for i in range(len(formatted_text)-1):
 if(formatted_text[i] == formatted_text[i+1]):
   formatted_text[i+1] = ''
formatted_text.remove('')
  • While this may be a duplicate of *some* question, it isn't a duplicate of the question cited (which is about iterating over elements, not indices). – Scott Hunter Jul 11 '19 at 18:37
  • 2
    Couple of valid answers below. If you would like to continue using the iteration over string method you can try going backwards through the list using `range(len(array)-2, 0, -1)`. Which would go from the second to last index (comparing to the last) to the first. That way removing elements won't affect the next index in order – Josh Jul 11 '19 at 18:41
  • try this : ```[x[1] for x in enumerate(my_list) if my_list[x[0]] != my_list[x[0]-1]]``` – Loïc Jul 11 '19 at 18:49
  • range(len(array)-2, 0, -1), yeah it's working thanks. But why -2? – Jan Kwiatkowski Jul 11 '19 at 18:52
  • @JanKwiatkowski: len(array)-1 would be the index of the last element; you want the one before that. – Scott Hunter Jul 11 '19 at 19:02

2 Answers2

0

Once you delete an element of formatted_text, there aren't as many elements as there were when you started, but the loop will proceed as if there are.

Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
0

Your loop is set up to run for this many iterations:

 range(len(formatted_text)-1)

If you remove items from your list then this range will be greater than the number of items you're checking, hence the out of range error you're seeing.

Will Jenkins
  • 9,507
  • 1
  • 27
  • 46