for i in list - change a list inside a for loop?
dsavitsk
dsavitsk at e-coli.net
Mon Mar 3 15:42:47 EST 2003
"Albert Hofkamp" <hat at se-46.wpa.wtb.tue.nl> wrote in message
news:slrnb66opl.g1l.hat at se-46.wpa.wtb.tue.nl...
> 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.
why not ...
while 1:
try:
x.remove('C')
except:
break
which might not be as fast [1], but is very readable.
[1] I have no idea about this, but it seems that it is going to loop less
times than the other options.
-d
More information about the Python-list
mailing list