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

Peng Yu pengyu.ut at gmail.com
Sat Nov 7 11:12:25 EST 2009


On Sat, Nov 7, 2009 at 8:54 AM, Steven D'Aprano
<steve at remove-this-cybersource.com.au> wrote:
> On Fri, 06 Nov 2009 10:16:58 -0600, Peng Yu wrote:
>
>> What is a list-comprehension?
>
> Time for you to Read The Fine Manual.
>
> http://docs.python.org/tutorial/index.html
>
>
>> I tried the following code. The list 'l' will be ['a','b','c'] rather
>> than ['b','c'], which is what I want. It seems 'remove' will disrupt the
>> iterator, right? I am wondering how to make the code correct.
>>
>> l = ['a', 'a', 'b', 'c']
>> for x in l:
>>   if x == 'a':
>>     l.remove(x)
>
>
> Oh lordy, it's Shlemiel the Painter's algorithm. Please don't do that for
> lists with more than a handful of items. Better still, please don't do
> that.
>
> http://www.joelonsoftware.com/articles/fog0000000319.html

I understand what is Shlemiel the Painter's algorithm. But if the
iterator can be intelligently adjusted in my code upon 'remove()', is
my code Shlemiel the Painter's algorithm?



More information about the Python-list mailing list