Back to General

Operations on Lists (Iterators & Amend) · General · Practice Question

Get the Unique Elements of a List

Sign in to track your progress

Question

Given:

l:3 1 4 1 5 9 2 6 5 3 5

Return the unique elements of l.

Expected result:

3 1 4 5 9 2 6

Solution

distinct l

Alternative Solution

key group l

Alternative Solution

l union l

Explanation

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.