If you want to get unique elements from a list and keep their original order, then you may employ OrderedDict data structure from Python's standard library:
from collections import OrderedDict
def keep_unique(elements):
return list(OrderedDict.fromkeys(elements).keys())
elements = [2, 1, 4, 2, 1, 1, 5, 3, 1, 1]
required_output = [2, 1, 4, 5, 3]
assert keep_unique(elements) == required_output
In fact, if you are using Python ≥ 3.6, you can use plain dict
for that:
def keep_unique(elements):
return list(dict.fromkeys(elements).keys())
It's become possible after the introduction of "compact" representation of dicts. Check it out here. Though this "considered an implementation detail and should not be relied upon".