What is the best way to delete strings in a string list that that match certain pattern?

Peter Otten __peter__ at web.de
Fri Nov 6 12:05:11 EST 2009


Peng Yu wrote:

> My problem comes from the context of using os.walk(). Please see the
> description of the following webpage. Somehow I have to modify the
> list inplace. I have already tried 'dirs = [i for i in l if dirs !=
> 'a']'. But it seems that it doesn't "prune the search". So I need the
> inplace modification of list.

Use

dirs[:] = [d for d in dirs if d != "a"]

or

try:
    dirs.remove("a")
except ValueError:
    pass
 





More information about the Python-list mailing list