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

mik3l3374 at gmail.com mik3l3374 at gmail.com
Wed Apr 4 05:16:09 EDT 2007


7stud wrote:
> On Apr 3, 3:53 pm, "bahoo" <b83503... at yahoo.com> wrote:
> > > target = "0024"
> > > l = ["0024", "haha", "0024"]
> >
> >
> > > 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.
>
> Prove it.
here's something:

>>> l = ["0024", "haha", "0024", "0024", "sfs"]
>>> target = "0024"
>>> for index, val in enumerate(l):
...  print "index: " , index , "value: " , val
...  del l[index]
...  print "after del: " , l
...
index:  0 value:  0024
after del:  ['haha', '0024', '0024', 'sfs']
index:  1 value:  0024
after del:  ['haha', '0024', 'sfs']
index:  2 value:  sfs
after del:  ['haha', '0024']
>>> l
['haha', '0024']




More information about the Python-list mailing list