Find Unique Values in List (Python)

I Googled this problem today and found a lot of people creating long-ish functions to find unique values. There is a much simpler solution: turn your list into a set (which removes duplicates) and then back into a list.

newList = list(set(oldList))

Hope this is of help to someone. Apologies if this is already a well-known solution. Perhaps “set” was unavailable in earlier (pre-2.7) versions of Python.

Update: This post generates a fair amount of traffic. Peter Bengtsson has some other options if you care more about speed/ordering/etc rather than simplicity, which was the goal here.

About these ads

About You Study Politics, Right?

Graduate student in political science at Duke University.
This entry was posted in Technical and tagged , . Bookmark the permalink.

3 Responses to Find Unique Values in List (Python)

  1. scintilla says:

    nice solution! However, I find it odd that (a) this was posted on new years eve, and (b) a political science student is using python. Please explain yourself :P

    • Thanks for your comment. I was creating a game over winter break in Python, and am now taking a ‘Python for Political Scientists’ class that’s one of the first of its kind (see more recent posts or whyhat.com for details).

  2. Pingback: Automatically Setup New R and LaTeX Projects | You Study Politics, Right?

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Connecting to %s