Python: Get unique elements in a list, sorted or unsorted

I ran into these two methods for grabbing just the unique elements from a list, one keeps the order, the other relies on sorting the list.

def uniq(list)
    # element order preserved
    set = {}
    return [ set.setdefault(x,x) for x in list if x not in set ]

def uniq(list)
    # element order not preserved
    set = {}
    map( set.__setitem__, list, [] )
    return set.keys()

But then I found some strange code that works really fast. Check out this amazing little one liner!

def getUniqueSynset(hasDupes):
    unique_trick = [ uniq for uniq in hasDupes if uniq not in locals()['_[1]'] ]
    return unique_trick
Posted by admica   @   3 March 2009

Related Posts

Like this post? Share it!

Digg Twitter StumbleUpon Delicious Technorati Facebook RSS

1 Comments

Comments
Jul 5, 2011
4:09 pm
#1 Felipe MacAuliffe :

Thank you very much !!! It works just great

Cheers from Chile, SouthAmerica

Leave a Comment

Name

Email

Website

Previous Post
« Your first Linux command on a dual boot system should be:
Next Post
The Linux Foundation is relaunching Linux.com »
Powered by Wordpress   |   Lunated designed by ZenVerse