Josh Glover Josh Glover - 1 year ago 121
Python Question

How to remove duplicates from Python list and keep order?

Given a list of strings, I want to sort it alphabetically and remove duplicates. I know I can do this:

from sets import Set
myHash = Set(myList)

but I don't know how to retrieve the list members from the hash in alphabetical order.

I'm not married to the hash, so any way to accomplish this will work. Also, performance is not an issue, so I'd prefer a solution that is expressed in code clearly to a fast but more opaque one.

Answer Source

A list can be sorted and deduplicated using built-in functions:

myList = sorted(set(myList))
  • set is a built-in function for Python >= 2.3
  • sorted is a built-in function for Python >= 2.4
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download