Sorting and Unique
Unique Values
Collect the distinct values from an 8-element list that contains repeats. A
dict accumulates each value as a key (ignoring duplicates), then sorted
produces the final ordered list. The replay shows seen filling up — its size
staying at 6 even though 8 elements are processed.
By hand
With NumPy
np.unique(a) returns a sorted array of unique values in one call. The output
shape (6,) is smaller than the input shape (8,) — unique reduces the
array.
naive.py
values = [3, 1, 4, 1, 5, 9, 3, 2]
seen = {}
for v in values:
seen[v] = True
unique = sorted(seen.keys())
print('RESULT:', unique)
library.py
import numpy as np
values = [3, 1, 4, 1, 5, 9, 3, 2]
a = np.array(values)
result = np.unique(a)
print('a: shape:', a.shape, 'dtype:', a.dtype, 'values:', a.tolist())
print('result: shape:', result.shape, 'dtype:', result.dtype, 'values:', result.tolist())
print('RESULT:', result.tolist())
a: shape: (8,) dtype: int64 values: [3, 1, 4, 1, 5, 9, 3, 2]
result: shape: (6,) dtype: int64 values: [1, 2, 3, 4, 5, 9]
RESULT: [1, 2, 3, 4, 5, 9]
Implementation notes
np.uniquealways sorts its output — the sorted order is part of the contract, not a side effect. The naivesorted(seen.keys())call at the print boundary matches this so both RESULT lines agree.np.unique(a, return_counts=True)also returns the count of each unique value, useful for frequency analysis.- The Python equivalent of unique is
sorted(set(values)). The dict approach here keeps the seen-key pattern visible in the replay (unlikeset, which has no meaningful step-by-step membership story for the tracer). - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.