List without duplicates?

jerry_spicklemire at my-deja.com jerry_spicklemire at my-deja.com
Fri Jun 23 18:50:48 EDT 2000


Greetings Gurus and Fellow Wannabes,

Just a minor "heads up" for a possible "gotcha".

It looks to me as if this method, though speedy, will return the
cleaned list in a much different order than the original, since the

  dict.keys()

method outputs in the (seemingly random) order of the dicts internal
hash table.

The moral is, if the order of the list members matters, be sure to wait
until after the cleaning step to sort, or at least remember to re-sort!

Later,
Jerry S.

In article <394FFA1A.FBF8F81D at roguewave.com>,
  Bjorn Pettersen <bjorn at roguewave.com> wrote:
> 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
>
>


Sent via Deja.com http://www.deja.com/
Before you buy.



More information about the Python-list mailing list