Operations on Lists (Iterators & Amend) · General · Practice Question
Get the Unique Elements of a List
Question
Given:
l:3 1 4 1 5 9 2 6 5 3 5Return the unique elements of l.
Expected result:
3 1 4 5 9 2 6Solution
distinct lAlternative Solution
key group lAlternative Solution
l union lExplanation
distinct is the direct, idiomatic way to drop duplicates from a list while preserving the order each value first appeared in.
The alternatives reach the same list without calling distinct directly. group l returns a dictionary mapping every distinct value in l to the list of positions it occurs at — its key is therefore exactly the set of distinct values, in first-seen order. l union l works because union itself is defined in terms of removing duplicates between two lists; unioning l with itself only ever keeps one copy of each value.