DEV Community

Mansour Moufid
Mansour Moufid

Posted on

3 2

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?

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay