-2

When I run this code:

li=["It","is","funny","how","I","fiddled","with","this"]
for i in range(0,len(li)):
    word=li[i]
    for j in range(0,len(word)-1):
        if word[j] == word[j+1]:
            li.pop(i)
            break
print(li)

My desired output is:

['It','is','how','I','with','this']

However, I get the following error message:

Traceback (most recent call last):
File "fiddle.py", line 3, in <module>
word=li[i]
IndexError: list index out of range

Please point out the mistake in my code.

DizzyBall
  • 17
  • 1
  • 4
  • Possible duplicate of [Remove items from a list while iterating](https://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating) – wwii Aug 18 '17 at 14:38
  • `i` changes from 0 to 7 during the loop. By the time `i` reaches 6, you have removed two items from the list so it only has six items in it and its *largest* index is 5 - that is why `li[6]` gives you an index error. printing variables at different places in a loop is a good simple troubleshooting tool that will show you what is happening while the code is running. – wwii Aug 18 '17 at 14:45

3 Answers3

2

The easiest way is to use a regular expression to identify duplicate runs of the same character in a string and put that in a list-comp, eg:

import re

li=["It","is","funny","how","I","fiddled","with","this"]
wanted = [el for el in li if not re.search(r'(.)\1', el)]

Gives you:

['It', 'is', 'how', 'I', 'with', 'this']
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
0

How about this:

new_list = [x for x in li if len(x) == len(set(x))]

Also, you should never iterate a list and remove elements while at it. The best approach is to create a new one

If you want to remove 2 identical chars together:

new_list = [x for x in li if not re.search(r'([a-zA-Z])\1', x)]
JBernardo
  • 32,262
  • 10
  • 90
  • 115
  • 2
    That'll only keep words with unique characters - I believe the OP is actually trying to only remove words that contain consecutive duplicate characters. – Jon Clements Aug 18 '17 at 14:29
  • @JBernardo You are right. I shouldn't have iterated the list and removed the elements at the same time. – DizzyBall Aug 18 '17 at 14:38
0

At this point:

for i in range(0,len(li)):

len(li) equals 8, so your loop goes from 0 to 7. However, since you're removing items from li inside the loop, li becomes shorter than 8 elements before i reaches 7. Then you get the error.

Błotosmętek
  • 12,717
  • 19
  • 29