Filtering a Python list to uniques

Raymond Hettinger python at rcn.com
Wed Mar 26 09:00:30 CET 2008


On Mar 25, 4:30 pm, kellygreer1 <kellygre... at yahoo.com> wrote:
> What is the best way to filter a Python list to its unique members?
> I tried some method using Set but got some "unhashable" error.
>
> lstone = [ 1, 2, 3, 3, 4, 5, 5, 6 ]
> # how do i reduce this to
> lsttwo = [ 1, 2, 3, 4, 5, 6 ]

If the elements are hashable, try this:
   lsttwo = sorted(set(lstone))
If not hashable, try:
   lsttwo = [k for k,v in itertools.groupby(sorted(lstone))]


Raymond



More information about the Python-list mailing list