List without duplicates?

Wolfgang Grafen Wolfgang.Grafen at marconicomms.com
Wed Jun 21 05:21:51 EDT 2000


> 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?
>

Try this ...

old_list = [1, 2, 3, 2, 1, 4, 3, 5, 2]


unique_list = []

for member in old_list:
   if not member in unique_list:
unique_list.append(member)

print unique_list
[1, 2, 3, 4, 5]


... or that ...

unique_list = []
for member in old_list:
    member not in unique_list and unique_list.append(member)

0
0
0
0
print unique_list
[1, 2, 3, 4, 5]

... or even following ...

unique_list = []

map(lambda member,unique_list=unique_list:
    member not in unique_list and unique_list.append(member),
    old_list)
[None, None, None, 0, 0, None, 0, None, 0]

>>> print unique_list
[1, 2, 3, 4, 5]
>>>

Wolfgang




More information about the Python-list mailing list