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

Thomas Nelson thn at mail.utexas.edu
Tue Apr 3 14:53:50 EDT 2007


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.
>
> It seems like regular expressions is the rescue, but I couldn't find
> the right tool.
>
> Thanks!
> bahoo

It's hard to imagine using regular expressions here.  Here's a simple
attempt:

def removeall(mylist,obj):
	while obj in mylist:
		mylist.remove(obj)

Or, if you don't need the changes in place:

[x for x in mylist if x!= obj]

Tom




More information about the Python-list mailing list