1

If I run this code:

a = ['bob','bob','bob','bob','bob','bob','bob']
b = ['bob']

for item in a:
    if item in b:
        a.remove(item)

I expect all the 'bob's to be removed, but there are 3 'bob's left. I don't understand. Someone please enlighten me, I think I may be losing my mind.

immeeh
  • 59
  • 5
  • 3
    Once you remove an element the list gets shorter but the index you are iterating at stays the same. This makes you skip an element. You are better off filtering with a list comp. `a = [i for i in a if i not in b]` – Primusa Apr 21 '18 at 17:03
  • 1
    If you don't care about the order of the list, you can create a new one by `set(a) - set(b)`. – tdelaney Apr 21 '18 at 17:09
  • This makes a lot of sense, the way it worked in my head is different. Thanks for the alternative code @Primusa – immeeh Apr 21 '18 at 17:15
  • For my purposes I don't care about order but I'll keep both ways in mind in the future thanks @tdelaney – immeeh Apr 21 '18 at 17:17

0 Answers0