Wednesday, 15 June 2011

A simple unique-ing function using Python

This may not be efficient, but it surely is simple and easy to understand. Let's say you have a list of singleton items and you wish to shrink that list down to only the unique items. Here's a simple function to achieve that:

def unique(input):
return list(set(input))

This works well for lists containing integers and strings. However, if you want to unique-ize a single string, here's a modification:

def unique(input):
return "".join(set(input))

Note that order preservation is not guaranteed.

No comments:

Post a Comment