You could (ab)use collections.OrderedDict
to get just the unique elements in order:
>>> list_1 = [1,3,2,2,3,4,5,1]
>>> from collections import OrderedDict
>>> list(OrderedDict((x, None) for x in list_1))
[1, 3, 2, 4, 5]
Alternatively, you could use a list comprehension with an additional set
of already seen items. However, list comprehensions with side-effects are not considered best style.
>>> list_1 = [1,3,2,2,3,4,5,1]
>>> seen = set()
>>> [x for x in list_1 if not (x in seen or seen.add(x))]
[1, 3, 2, 4, 5]
The condition not (x in seen or seen.add(x))
works like this: If x in seen
, the or
is true and thus the not
is false, but if x not in seen
, then the first part of the or
is false, and thus the second part is executed and returns None
, which is then converted to True
by not
.