Best way to find unique items in a list

Jim Richardson warlock at eskimo.com
Fri Feb 25 13:54:43 EST 2000


On Thu, 24 Feb 2000 11:31:32 +0100, 
 maxm, in the persona of <maxm at normik.dk>,
 brought forth the following words...:

>I have written the following snippet to return a list of unique items in
>another list. I just wondered if there was a smarter/faster way of doing it?
>
>Anyone for a little brain gym?
>
>------------------------------------------
>
>def Unique(theList):
>    uniqueList = []
>    OldValue = ''
>    theList.sort()
>    for value in theList:
>        if OldValue != value:
>            uniqueList.append(value)
>        OldValue = value
>    return uniqueList
>
>
>print Unique(['Max','Gitte','Magnus','Caroline','Clara','Max','Gitte'])
>
>>>>['Caroline', 'Clara', 'Gitte', 'Magnus', 'Max']
>
>------------------------------------------
>
This works also, seems to be no slower, if not a little bit
faster, at least for the list example given, I haven't tried it
with other lists. This works because dict assignment overwrites
any previous key. Of course, a downside is that  the result is in
no particular order, if that matters, you can sort the result.



def uneek(list):
	val_dict={}
	for val in list:
  		val_dict[val]=''
	return val_dict
	  
print uneek(['Max','Gitte','Magnus','Caroline','Clara','Max','Gitte']).keys()

-- 
Jim Richardson
	Anarchist, pagan and proud of it
WWW.eskimo.com/~warlock
	Linux, because life's too short for a buggy OS.




More information about the Python-list mailing list