Terry Reedy <[EMAIL PROTECTED]> wrote:

> "Alex Martelli" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> > for item in alist:
> >    if isnasty(item):
> >        alist.remove(item)
> >
> > changing the header to ``in alist[:]:'' or ``in list(alist):'' probably
> > makes this code work, but it still can't make it GOOD... good would be:
> >
> > alist[:] = [item for item in alist if not isnasty(item)]
> 
> Given that the OP has verified that replacing alist with list(alist) in the
> for statement solves his problems, 

...and that of course is crucial (using list(alist) vs alist[:] is of
course quite minor, just my pet peeve that some of us old Pythonistas go
around doign the [:] bit as if it was obvious rather than the clearer
list() call;-)...

> I agree that the listcomp is even nicer 
> in that it avoids the bug trap, the over-copying of the entire list, the
> alternative of iterating in reverse, and the n**2 behavior of multiple
> correct deletes from a long list.

Right, the O(N**2) is generally the biggie (copying the entire list is
just O(N), and with a small multiplicative constant anyway).  2.4's
``reversed'' built-in is nice for those case in which you do need
reverse iteration, of course.  But list comprehensions are often even
better for such tasks as "remove all items such that p(item)"...


Alex
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to