Duplicates in lists

Jeff Pinyan jeffp at crusoe.net
Fri Mar 10 13:38:14 CET 2000

[posted & mailed]

On Mar 10, Quinn Dunkan said:

>>> is there someone who has an efficient function that finds
>>> all duplicates in a list?

>def uniq(a):
>    r = {}
>    for i in a:
>        r[i] = None
>    return r.keys()

Your approach loses the order of the keys.  If this is not acceptable, I

  def ord_uniq(a):
    r = {}
    ret = []
    for i in a:
      if not r.has_key(i):
        r[i] = 1
    return ret

Or, using OrderedDict.py:

  def ord_uniq(a):
    r = OrderedDict.OrderedDict()
    for i in a: r[i] = 1
    return r.keys()

MIDN 4/C PINYAN, NROTCURPI, US Naval Reserve             japhy at pobox.com
http://www.pobox.com/~japhy/                  http://pinyaj.stu.rpi.edu/
PerlMonth - An Online Perl Magazine            http://www.perlmonth.com/
The Perl Archive - Articles, Forums, etc.    http://www.perlarchive.com/

More information about the Python-list mailing list