Best way to make a list unique?
Diez B. Roggisch
deetsNOSPAM at web.de
Tue Mar 8 05:34:24 EST 2005
Eric Pederson wrote:
> I have
>
>>>> listA=[1,2,3,4,5,4,3,4,3,2,1]
>
> and I want a list of only the unique members.
>
> This seems inefficient, but works fine over my small sample lists:
>
>>>> listA=[a for a in set(listA)]
>
>
> Is there a more efficient approach for cases where listA is large?
No. But I doubt that that is what you actually want, as listA will lose its
order afterwards. Typically, something like that gets written like this:
inserted = set()
res = []
for e in listA:
if not e in inserted:
res.append(e)
inserted.add(e)
listA = res
Or, with a little helperfunction:
inserted = set()
def foo(e):
inserted.add(e)
return e
listA = [foo(e) for e in listA if not e in inserted]
But ist's not really much better.
--
Regards,
Diez B. Roggisch
More information about the Python-list
mailing list