-4

As you can see, i'm trying to delete the word in a list whose length is 1 or 2, but "P" and "ye" can't be found and removed!

enter image description here

enter image description here

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • you're modifying the list as y ou iterate it. – Neil G Sep 26 '16 at 09:56
  • 1
    Possible duplicate of [Remove items from a list while iterating in Python](http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) – SiHa Sep 26 '16 at 10:14

2 Answers2

0

Check out this code:

li = ['of','in','a','bb','abbb']
lii = []
for i in li:
  j = len(i)
  if j == 1 or j == 2:
    lii.append(i)

for i in lii:
  li.remove(i)

print li

Output:

['abbb']
User_Targaryen
  • 4,125
  • 4
  • 30
  • 51
0

You can't modify list while you iterate through it. But you can do something like this:

L = ['of', 'P', 'representig', 'the', 'subs', 'et', 'ye', 'ti']

result = [i for i in L if len(i) != 1 and len(i) != 2]
zipa
  • 27,316
  • 6
  • 40
  • 58