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

Hendrik van Rooyen mail at microcorp.co.za
Wed Apr 4 02:37:30 EDT 2007


"bahoo" <b83...4 at yahoo.com> wrote:


> On Apr 3, 2:31 pm, "Matimus" <mccre... at gmail.com> wrote:
> > It depends on your application, but a 'set' might really be what you
> > want, as opposed to a list.
> >
> > >>> s = set(["0024","haha","0024"])
> > >>> s
> >
> > set(["0024","haha"])>>> s.remove("0024")
> > >>> s
> >
> > set(["haha"])
> 
> This sounds cool.
> But is there a command I can convert the "set" back to a "list"?
> 

Here is a general way to find the duplicates:

>>> duplist
[1, 2, 3, 4, 'haha', 1, 2, 3, 4, 5]
>>> copylist = duplist[:]
>>> for x in duplist:
 del(copylist[copylist.index(x)])
 if x in copylist:
  fullset.remove(x)
  
>>> fullset
set([5, 'haha'])
>>> list(fullset)
[5, 'haha']
>>> 

hth - Hendrik




More information about the Python-list mailing list