0

I have this code

l = ['vbg', 'vkb', 'vv', 'vbj', 'vz',...] #the list continues 

for x in l:
    if len(x) > 2:
        i = l.index (x)
        l.pop(x)
print (l)

Output:

['vkb','vv','vz']

My desired output is this:

['vv','vz']

I know why this happening but I don't know how to fix this

Ibrahim
  • 798
  • 6
  • 26
  • 2
    Golden rule: Never mutate a list while iterating on it. – Ukiyo Nov 24 '20 at 07:59
  • 3
    dont modify a list while iterating, create a new one: use `list(filter(lambda x: len(x) < 3,l))` or a list comprehension: `[e for e in l if len(e) < 3]` – Patrick Artner Nov 24 '20 at 07:59
  • In this particular case, the iteration "skip" the value `vkb` because its index becomes the index on which the iteration has just occurred after the pop of `vbg`. So, in a hypothetical list of values that all have more than 2 characters, only one element every two will always be deleted – lorenzozane Nov 24 '20 at 08:03
  • @PatrickArtner I ran the lambda function but it didn't do anything – Ibrahim Nov 24 '20 at 08:05
  • The lamba works properly, did you saved the result somewhere? – lorenzozane Nov 24 '20 at 08:07

0 Answers0