Issue With Removing List Elements in for Loop
It seems Python does not permit to remove elements from the list while iterating over it using a for loop. I will provide a quick workaround for this to solve.
This issue can be not an actual bug and can be caused by the pointer arithmetic handled in the background. It requires further research to get the root cause.
However lets exemplify the issue. Let’s say you have list with items:
letters = ["a","b","c","d"]
and you want to remove items until only letter “b” is left.
You can write:
for letter in letters:
if "b" != letter:
letters.remove(letter)
Unfortunately it will return:
>>> letters
['b', 'd']
This is wrong and not the expected output.
The workaround would be is using the copy of that list during iteration:
for letter in letters[:]:
if "b" != letter:
letters.remove(letter)
We have now the correct output as below:
>>>letters
['b']