for i in list - change a list inside a for loop?

Anton Muhin antonmuhin at
Sat Mar 1 20:11:20 CET 2003

Klaus Meyer wrote:
> Hi,
> it is OK to change a list inside a for loop?
> Example:
> x=range(100)
> for i in x:
>    del x[-1]
> Another Question:
> How to remove a found element from a list in a for-loop?
> x=["A", "B", "C", "D"]
> for i in x:
>     if i=="C": del x[this one, but how?]

You may use filter or list comprehensions as well:

x = [e for e in x if x != "C"]


x = filter(lambda e: e != "C", x)

More Pythonic approach might be:

r = []
for i in x:
     if i != "C":

If you are working with hude lists, iterator version of filter might be 
of help.


More information about the Python-list mailing list