os.path.walk not pruning descent tree (and I'm not happy with that behavior?)

Maric Michaud maric at aristote.info
Mon May 28 04:25:18 EDT 2007


I'm really sorry, for all that private mails, thunderbird is awfully 
stupid dealing with mailing lists folder.


Gabriel Genellina a écrit :
> En Sun, 27 May 2007 22:39:32 -0300, Joe Ardent <ardent at gmail.com> escribió:
> 
> 
> - iterate backwards:
> 
> for i in range(len(names)-1, -1, -1):
>    fname = names[i]
>    if fname[:1]=='.':
>      names.remove(fname)
> 

This is not about iterating backward, this is about iterating over the
index of each element instead of iterating over the element (which must
be done begining by the end). In fact this code is both inefficient and
contains a subtle bug. If two objects compare equals in the list, you
will remove the wrong one.

It should be :

for i in range(len(names)-1, -1, -1):
    if names[i][:1]=='.':
      del names[i]


> - filter and reassign in place 

Seems the best here.

> (the [:] is important):

Not so. Unless "names" is referenced in another namespace, simple
assignment is enough.

> names[:] = [fname for fname in names if fname[:1]!='.']
> 
> (Notice that I haven't used a regular expression, and the remove method)
> 





More information about the Python-list mailing list