One liner in python to get a uniquified list

In almost every list processing from various sources, we need to unique elements in the list. Here is an easy method to do so.


orig_list = [1,2,"a",3,3,2,"tux"]
unique_list = list(set(orig_list))

print unique_list
>>> ['a', 1, 2, 3, 'tux']

This doesn’t preserve the order of the list. If you want to preserve the order you may want to do something like this

unique_list = list(set(orig_list))
unique_list.sort(cmp = lambda x,y: cmp(orig_list.index(x), orig_list.index(y)))

About these ads
  1. You might want to take a look at Fastest way to uniqify a list in Python. It has quite a few different solutions to this problem, both order-preserving and not.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: