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

Albert Hofkamp hat at se-46.wpa.wtb.tue.nl
Mon Mar 3 09:14:12 EST 2003


On Sat, 01 Mar 2003 19:37:03 +0100, Klaus Meyer <km-news1 at onlinehome.de> wrote:
> 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?]

I normally construct a new list on the fly as in

newlist=[]
for i in x:
   if i!='C': newlist.append(i)
x=newlist

This is very clear code, and since Python does reference counting the
elements are not really copied, so speed should be managable.
 


-- 
Albert
-- 
Unlike popular belief, the .doc format is not an open publically available format.




More information about the Python-list mailing list