In Python, we can get the unique items of the list using set(list). However doing this breaks the order in which the values appear in the original list. Is there an elegant way to get the unique items in the order in which it appears in the list.
Asked
Active
Viewed 616 times
2
rambalachandran
- 1,862
- 2
- 16
- 29
-
If `numpy` works, there are [several questions out there](http://stackoverflow.com/questions/12926898/numpy-unique-without-sort). Otherwise "stable unique" might be a keyword. – Andras Deak -- Слава Україні Sep 28 '16 at 18:51
-
@AndrasDeak Thank you. Yes I only have integer datatypes at the moment and the result you pointed to should work. – rambalachandran Sep 28 '16 at 18:53
-
Needless to say, don't call it `list`;) – Andras Deak -- Слава Україні Sep 28 '16 at 18:57
2 Answers
6
This is an elegant way:
from collections import OrderedDict
list(OrderedDict.fromkeys(list))
It works if the list items are all hashable (you will know that all the list items are hashable if converting it to a set did not trigger an exception).
If any items are not hashable, there's an alternative which is more robust at the price of poorer performance: I refer you to the answer from Patrick Haugh.
-
Note that your non-hashable update is already present in an answer from earlier, so it's a bit redundant in this answer. – Andras Deak -- Слава Україні Sep 28 '16 at 19:02
1
l = []
for item in list_:
if item not in l:
l.append(item)
This gets slow for really big, diverse list_. In those cases, it would be worth it to also keep track of a set of seen values.
Patrick Haugh
- 55,247
- 13
- 83
- 91