Best way to make a list unique?

Max M maxm at mxm.dk
Tue Mar 8 07:09:07 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. Even though the code can be a little simpler:

listA = list(Set(listA))

You don't even need to convert it to a list. You can just iterate over 
the set.

 >>> la = [1,2,3,4,3,2,3,4,5]
 >>> from sets import Set
 >>> sa = Set(la)
 >>> for itm in sa:
...     print itm
1
2
3
4
5

-- 

hilsen/regards Max M, Denmark

http://www.mxm.dk/
IT's Mad Science



More information about the Python-list mailing list