Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicates from Python list and keep order? [duplicate]

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.

like image 887
Josh Glover Avatar asked Jan 26 '09 14:01

Josh Glover


People also ask

How do you preserve the order of a list in Python?

fromkeys(list)) that goes through two phases: (1) Convert the list to a dict using the dict. fromkeys() function with the list elements as keys and None as dict values. (2) Convert the dictionary back to a list using the list() constructor. As dictionaries preserve the order of the keys, the list ordering is preserved.


1 Answers

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
like image 88
Rod Daunoravicius Avatar answered Oct 11 '22 19:10

Rod Daunoravicius