Consider a Python list my_list
containing [\'foo\', \'foo\', \'bar\']
.
What is the most Pythonic way to uniquify and sort a list ?
(thi
Others have mentioned sorted(set(my_list)), which works for hashable values such as strings, numbers and tuples, but not for unhashable types such as lists.
To get a sorted list of values of any sortable type, without duplicates:
from itertools import izip, islice
def unique_sorted(values):
"Return a sorted list of the given values, without duplicates."
values = sorted(values)
if not values:
return []
consecutive_pairs = izip(values, islice(values, 1, len(values)))
result = [a for (a, b) in consecutive_pairs if a != b]
result.append(values[-1])
return result
This can be further simplified using the "pairwise" or "unique_justseen" recipes from the itertools documentation.