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

Hendrik van Rooyen mail at microcorp.co.za
Wed Apr 4 09:56:34 EDT 2007


 
> On Apr 3, 3:53 pm, "bahoo" <b8....3... at yahoo.com> wrote:


My first submission handles duplicates, but not triplicates and more.
Here is one that seems a bit more bulletproof:

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

print list(fullset)

when it is run, I get:

IDLE 1.1.3      ==== No Subprocess ====
>>> 
[5, 6, 'haha']
>>> 

Now how would one do it and preserve the original order?
This apparently simple problem is surprisingly FOS...
But list comprehension to the rescue :

>>>[x for x in duplist if duplist.count(x) == 1]
['haha', 5, 6]
>>> 

*shakes head* duh... why does it take so long?

: - (

- Hendrik




More information about the Python-list mailing list