os.walk bug?

Alex Martelli aleaxit at yahoo.com
Sat Dec 18 22:18:21 CET 2004

Terry Reedy <tjreedy at udel.edu> wrote:

> "Alex Martelli" <aleaxit at yahoo.com> wrote in message 
> news:1goxmng.1edap1z1cok1cnN%aleaxit at yahoo.com...
> > 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)"...


More information about the Python-list mailing list