Python Practice › NumPy Programs › Program 55

Unique elements

EasyNumPy Programs · 55 of 100

Write a NumPy program to get the unique elements of an array.

Advertisement
Input
[25, 33, 10, 45, 33, 10]
Output
[10 25 33 45]
[25 33 10 45]

Approach

  1. np.unique returns them sorted; use the index to keep first-seen order.

Solution

Python
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.

More numpy programs

← All 100 NumPy Programs

Leave a Comment