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

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Wed Apr 4 06:55:32 EDT 2007


bahoo a écrit :
> 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.
> 
> It seems like regular expressions is the rescue, 

Nope. re wouldn't help here - it works on strings, not on lists (you 
need to understand that in Python, strings are *not* 'lists of chars').

Use list comps:
   mylist = [item for item in mylist if item != '0024']

or filter() :
   mylist = filter(lambda item: item != '0024', mylist)


> but I couldn't find
> the right tool.

May I second Grant Edward's suggestion in previous thread ? You'd really 
do yourself a favor by following a couple Python tutorials. I'd say the 
one in the official doc, and Dive into Python.



More information about the Python-list mailing list