how to remove multiple occurrences of a string within a list?

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Tue Apr 3 22:14:47 EDT 2007


On Tue, 03 Apr 2007 11:20:33 -0700, bahoo wrote:

> Hi,
> 
> I have a list like ['0024', 'haha', '0024']
> and as output I want ['haha']
> 
> If I
> myList.remove('0024')
> 
> then only the first instance of '0024' is removed.

There are a whole heap of ways of doing this. They all have in common the
idea of doing something over and over again until you're finished.

Here's one way, using a loop in a try...except block.

try:
    while True:
        myList.remove('0024')
        # raises an exception when the target isn't in the list any more
except ValueError:
    pass # we're done


> It seems like regular expressions is the rescue, 

Since when did reg exes operate on lists?



-- 
Steven D'Aprano 




More information about the Python-list mailing list