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

Peter Otten __peter__ at web.de
Sat Nov 7 19:47:41 CET 2009


Robert P. J. Day wrote:

> On Sat, 7 Nov 2009, Peng Yu wrote:
> 
>> On Fri, Nov 6, 2009 at 5:57 PM, Dave Angel <davea at ieee.org> wrote:
> 
>> > But if you have an expression you want to match each dir against,
>> > the list comprehension is the best answer.  And the trick to
>> > stuffing that new list into the original list object is to use
>> > slicing on the left side.  The [:] notation is a default slice
>> > that means the whole list.
>> >
>> > dirs[:] = [ item for item in dirs if     bool_expression_on_item ]
>>
>> I suggest to add this example to the document of os.walk() to make
>> other users' life easier.
> 
>   huh?  why do you need the slice notation on the left?  why can't you
> just assign to "dirs" as opposed to "dirs[:]"?  using the former seems
> to work just fine.  is this some kind of python optimization or idiom?

dirs = [...]

rebinds the name "dirs" while

dirs[:] = [...]

updates the contents of the list currently bound to the "dirs" name. The 
latter is necessary in the context of os.walk() because it yields a list of 
subdirectories, gives the user a chance to update it and than uses this 
potentially updated list to decide which subdirectories to descend into.
A simplified example:

>>> def f():
...     items = ["a", "b", "c"]
...     yield items
...     print items
...
>>> for items in f():
...     items = ["x", "y"]
...
['a', 'b', 'c']
>>> for items in f():
...     items[:] = ["x", "y"]
...
['x', 'y']

Peter




More information about the Python-list mailing list