Issue
In Python, we can get the unique items of a list L
by using set(L)
. 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 they appear in the list?
Solution
If all of the items in the list are hashable, then a dictionary can be used for an order-preserving dedupe:
L = list(dict.fromkeys(L))
For older Python versions (<= 3.6) where the standard dict is not order preserving, you can do the same thing using a collections.OrderedDict
.
If any of the list items are unhashable, there will be a TypeError
. You can use an alternative approach in this case, at the price of poorer performance. I refer you to the answer from Patrick Haugh.
Answered By - wim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.