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

bahoo b83503104 at yahoo.com
Tue Apr 3 17:53:55 EDT 2007


On Apr 3, 3:01 pm, "7stud" <bbxx789_0... at yahoo.com> wrote:
> On Apr 3, 12:20 pm, "bahoo" <b83503... at yahoo.com> 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
>
> Here are a couple of ways:
>
> target = "0024"
> l = ["0024", "haha", "0024"]
>
> ------------------------------------
> while(True):
>     try:
>         l.remove(target)
>     except ValueError:
>         break
>
> print l
> -------------------------------------
>
> for index, val in enumerate(l):
>     if val==target:
>         del l[index]
>
> print l

This latter suggestion (with the for loop) seems to be buggy: if there
are multiple items in the list "l" equal to "target", then only the
first one will be removed!

Thanks anyways.





More information about the Python-list mailing list