good solution ,thanks~!<br><br><div class="gmail_quote">2009/9/15 Steven D'Aprano <span dir="ltr"><<a href="mailto:steven@remove.this.cybersource.com.au">steven@remove.this.cybersource.com.au</a>></span><br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
On Mon, 14 Sep 2009 18:55:13 -0700, Chris Rebert wrote:<br>
<br>
> On Mon, Sep 14, 2009 at 6:49 PM, Helvin <<a href="mailto:helvinlui@gmail.com">helvinlui@gmail.com</a>> wrote:<br>
...<br>
<div class="im">> > I have looked at documentation, and how strings and lists work, but I<br>
> > cannot understand the behaviour of the following:<br>
</div>...<br>
> > for item in list:<br>
> > if item is ' ':<br>
> > print 'discard these: ',item<br>
> > index = list.index(item)<br>
> > del list[index]<br>
<br>
...<br>
<br>
> Moral: Don't modify a list while iterating over it. Use the loop to<br>
> create a separate, new list from the old one instead.<br>
<br>
<br>
This doesn't just apply to Python, it is good advice in every language<br>
I'm familiar with. At the very least, if you have to modify over a list<br>
in place and you are deleting or inserting items, work *backwards*:<br>
<br>
for i in xrange(len(alist), -1, -1):<br>
item = alist[i]<br>
if item == 'delete me':<br>
del alist[i]<br>
<br>
<br>
This is almost never the right solution in Python, but as a general<br>
technique, it works in all sorts of situations. (E.g. when varnishing a<br>
floor, don't start at the doorway and varnish towards the end of the<br>
room, because you'll be walking all over the fresh varnish. Do it the<br>
other way, starting at the end of the room, and work backwards towards<br>
the door.)<br>
<br>
In Python, the right solution is almost always to make a new copy of the<br>
list. Here are three ways to do that:<br>
<br>
<br>
newlist = []<br>
for item in alist:<br>
if item != 'delete me':<br>
newlist.append(item)<br>
<br>
<br>
newlist = [item for item in alist if item != 'delete me']<br>
<br>
newlist = filter(lambda item: item != 'delete me', alist)<br>
<br>
<br>
<br>
Once you have newlist, you can then rebind it to alist:<br>
<br>
alist = newlist<br>
<br>
or you can replace the contents of alist with the contents of newlist:<br>
<br>
alist[:] = newlist<br>
<br>
<br>
The two have a subtle difference in behavior that may not be apparent<br>
unless you have multiple names bound to alist.<br>
<br>
<br>
<br>
--<br>
<font color="#888888">Steven<br>
</font><div><div></div><div class="h5">--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</div></div></blockquote></div><br>