get rid of duplicate elements in list without set

Paul McGuire ptmcg at austin.rr.com
Fri Mar 20 16:34:23 CET 2009


On Mar 20, 9:54 am, "thomasvang... at gmail.com"
<thomasvang... at gmail.com> wrote:
> You could use:
> B=list(set(A)).sort()
> Hope that helps.
> T

That may hurt more than help, sort() only works in-place, and does
*not* return the sorted list.  For that you want the global built-in
sorted:

>>> data = map(int,"6 1 3 2 5 2 5 4 2 0".split())
>>> print sorted(list(set(data)))
[0, 1, 2, 3, 4, 5, 6]

To retain the original order, use the key argument, passing it a
function - simplest is to pass the index of the value in the original
list:

>>> print sorted(list(set(data)), key=data.index)
[6, 1, 3, 2, 5, 4, 0]

If data is long, all of those calls to data.index may get expensive.
You may want to build a lookup dict first:

>>> lookup = dict((v,k) for k,v in list(enumerate(data))[::-1])
>>> print sorted(list(set(data)), key=lookup.__getitem__)
[6, 1, 3, 2, 5, 4, 0]

-- Paul



More information about the Python-list mailing list