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

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Sat Mar 1 13:53:50 EST 2003


Klaus Meyer wrote:
> it is OK to change a list inside a for loop?

No, it's not. Or rather it is. Depends on your own code.
Better read about it in the Language Reference,
http://www.python.org/doc/current/ref/for.html

Generally, I find it better to just iterate over a copy,
and change the original list.

> 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?]

Eh.. no need to search for the element in the list.
This is painfully slow.

Just write:

	x.remove("C")

if you need to remove "C" from the list x.

Irmen.





More information about the Python-list mailing list