List without duplicates?

Bjorn Pettersen bjorn at roguewave.com
Tue Jun 20 19:11:22 EDT 2000


William Dandreta wrote:
> 
> Is there a built in Python function that eliminates duplicates in a list?
> 
> I have been sorting the list and compairing adjacent elements and if equal
> deleting one:
> -------------------------------
> mylist.sort()
>     j = len(mylist)-1
>     while j > 0:
>       if mylist[j] == mylist[j-1]:
>         del mylist[j]
>       j = j - 1
> ------------------------------------
> I recently tried using a dictionary. The list is the keys and I put and
> empty string for the entry
> --------------------
> mydict = {}
> for e in mylist:
>   if mydict.has_key(e): continue
>   else: mydict[e] = ''
> ------------------------------------
> Is ther a better way?
> 
> Bill

This should probably be a faq by now...:

def unique(lst):
    d = {}
    for item in lst:
        d[item] = None
    return d.keys()

-- bjorn




More information about the Python-list mailing list