Do you need to remove duplicates from a list, and keep it in order?
xs = [1, 3, 2, 2, 5, 4, 1, 5]
The set type will return one of each element:
>>> set(xs)
{1, 2, 3, 4, 5}
But not in order, because a set is an unordered collection.
>>> for x in set(xs):
... print(x)
...
1
2
3
4
5
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]
Quiz: When does the above construct not work?
Top comments (0)