What is the cleanest way to do a sort plus uniq on a Python list?

knorv picture knorv · May 28, 2010 · Viewed 63.7k times · Source

Consider a Python list my_list containing ['foo', 'foo', 'bar'].

What is the most Pythonic way to uniquify and sort a list ?
(think cat my_list | sort | uniq)

This is how I currently do it and while it works I'm sure there are better ways to do it.

my_list = []
...
my_list.append("foo")
my_list.append("foo")
my_list.append("bar")
...
my_list = set(my_list)
my_list = list(my_list)
my_list.sort()

Answer

Ignacio Vazquez-Abrams picture Ignacio Vazquez-Abrams · May 28, 2010
my_list = sorted(set(my_list))