+4 votes
in Programming Languages by (28.5k points)
How can I remove duplicate elements of a Python list as well as sort them?

1 Answer

+3 votes
by (48.9k points)

Using set(), you can eliminate duplicate elements from a list; then you can apply sorted().

Here is the one-liner code to sort and remove duplicate elements.

>>> x=['a','b','c','a','d','f','c','g','b']
>>> x
['a', 'b', 'c', 'a', 'd', 'f', 'c', 'g', 'b']
>>> sorted(set(x))
['a', 'b', 'c', 'd', 'f', 'g']