Tuesday, June 2, 2009

Finding Unique Values in Python

Here is a nice script example of how to find a unique value.

def UniqueValueList(value, vallist):
found = False
for listItem in vallist:
if listItem == value:
found = True
if found == False:
return vallist

This returns a list of values. The inputs are the value you want to see if it's unique and the array list you are storing your values in.

To declare the python array all you need to do is the following:
ValueList = []

So the proper call of this function would be
ValueList = UniqueValueList(value, ValueList)


MoonChild said...

There is a much easier method to find unique values in a list. There is the set() command (if you are using Python 2.5.2) which does this for you much faster.

The idea is:
myList = ["100", 200", "300", "100"]
mySet = set(myList)

If you print mySet you will get the following:

set("100", "200", "300")

The set acts like a list, so you can do:
for item in mySet:
print item

Or for fast membership testing:
"100" in mySet -> Returns True

Andrew said...

Great tip, I'm going to use that one for now on