for i in list - change a list inside a for loop?
Anton Muhin
antonmuhin at sendmail.ru
Sat Mar 1 14:11:20 EST 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"]
or
x = filter(lambda e: e != "C", x)
More Pythonic approach might be:
r = []
for i in x:
if i != "C":
r.append(i)
If you are working with hude lists, iterator version of filter might be
of help.
HTH,
Anton.
More information about the Python-list
mailing list