DEV Community

Mansour Moufid
Mansour Moufid

Posted on

Python unique list, in order

Do you need to remove duplicates from a list, and keep it in order?

xs = [1, 3, 2, 2, 5, 4, 1, 5]
Enter fullscreen mode Exit fullscreen mode

The set type will return one of each element:

>>> set(xs)
{1, 2, 3, 4, 5}
Enter fullscreen mode Exit fullscreen mode

But not in order, because a set is an unordered collection.

>>> for x in set(xs):
...     print(x)
... 
1
2
3
4
5
Enter fullscreen mode Exit fullscreen mode

Instead, first construct a set from the list, then a list from this set, in the right order with the sorted function, like so:

>>> xs = [1, 3, 2, 2, 5, 4, 1, 5]
>>> list(sorted(set(xs), key=lambda x: xs.index(x)))
[1, 3, 2, 5, 4]
Enter fullscreen mode Exit fullscreen mode

Quiz: When does the above construct not work?

Discussion (0)