Python Practice › NumPy Programs › Program 55
Unique elements
Write a NumPy program to get the unique elements of an array.
Input
[25, 33, 10, 45, 33, 10]
Output
[10 25 33 45] [25 33 10 45]
Approach
np.uniquereturns them sorted; use the index to keep first-seen order.
Solution
import numpy as npa = np.array([25, 33, 10, 45, 33, 10])print(np.unique(a))_, first = np.unique(a, return_index=True)print(a[np.sort(first)])Output
[10 25 33 45] [25 33 10 45]
Line by line
Lines 4-5
return_index gives each value’s first position; sorting those keeps the original order.
Learn the concept
New to this topic? Read the lesson, then come back.