How can I loop through a list of strings?
Question: I have this code:

    
    
    test = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O"]
    
    for i in test:
        if i not in ["C","D"]:
            test.remove(i)
    
    print(test)
    

I was expecting to get `['C','D']` as a result of running the code above,
however I am getting this `['B', 'C', 'D', 'F', 'H', 'J', 'L', 'N']`

How can I successfully loop through a list of strings and delete the elements
I don't need using Python 3?

**NOTE:** I don't want to use comprehension lists

thanks


Answer: When removing from lists in other languages, I used to reverse walk the list:

    
    
    test = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O"]
    
    for i in reversed(test):
        if i not in ["C","D"]:
            test.remove(i)
    
    print(test)
    

Note that `reversed` will create a new list so this might not be the best
solution for large lists. Now, since you already walk a copy of your list, and
if you need to parse in the correct order, you can use `copy`:

    
    
    import copy
    for i in copy.copy(test):
        if i not in ["C","D"]:
            test.remove(i)
    

and to avoid the import (from
[here](http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-
in-python)):

    
    
    for i in test[:]:
        if i not in ["C","D"]:
            test.remove(i)
    

Finally, the best solution for me, is a traditional, in-place reverse
iteration without copying the list ("borrowed" and modified from
[this](http://stackoverflow.com/a/6024599/3727050) answer)

    
    
    for i in range(len(test) - 1, -1, -1):
        if test[i] not in ["C","D"]:
            del test[i]
    

