0

I wrote a for loop that supposedly removes any elements that fits the description.

Example:

for tag in tags:
    if tag.lower() in ['ex1', 'ex2', 'ex3']:
        tags.remove(tag)

My tags would look like ['EX1', 'EX2', 'ex1', 'ex2', 'ex3', 'ex4', 'ex5'] and I expect to keep only ex4 and ex5

What I noticed is that the for loop would skip some elements, giving me results like ['EX2', 'ex2', 'ex4', 'ex5']

I suspect this being indexing issue, but I'm not sure if that's really the case.

I ended up using a list comprehension, which does the job correctly, but I just want to understand the true reason behind the unexpected behavior.

JChao
  • 2,178
  • 5
  • 35
  • 65

1 Answers1

1

Python has a hard time iterating through something that is being changed during the iteration. You can instead use a copy:

for tag in tags[:]:
    if tag.lower() in ['ex1', 'ex2', 'ex3']:
        tags.remove(tag)
zondo
  • 19,901
  • 8
  • 44
  • 83
  • yea I used a list comprehension at the end. `tags = [tag for tag in tags if tag.lower() not in ['ex1', 'ex2', 'ex3']]` Just want to understand the reason behind it. Thanks! – JChao Mar 03 '16 at 23:44