# Check if all elements in a NumPy array are unique

This tutorial will discuss about unique ways to check if all elements in a numpy array are unique.

## Technique 1: Using numpy.unique()

The `numpy` module in Python provides a method `unique()`. It accepts an array as an argument, and returns an array containing sorted unique elements from the passed array.

So, to check if a NumPy array contains only unique values, pass it to the `numpy.unique()` method, and compare the size of retuned array with the size of original array. If the size is same, then it means that this NumPy array has only unique values.

Let’s see the complete example,

```import numpy as np

# Create an NumPy array
arr = np.array([23, 56, 32, 14, 76, 44, 33])

# Check if all values in a numpy array are unique
if np.unique(arr).size == arr.size:
print("All elements are unique in the numpy array")
else:
print("All elements are not unique in the numpy array")
```

Output

```All elements are unique in the numpy array

```

## Technique 2: Using Set

A Set in Python can contain only unique elements. We can create a Set from a NumPy Array. The Set will have only unique values from the array. If size of Set and NumPy array is equal, then it means that the NumPy Array has only unique values.

Let’s see the complete example,

```import numpy as np

# Create an NumPy array
arr = np.array([23, 56, 32, 14, 76, 44, 33])

# Check if all values in a numpy array are unique
if len(set(arr)) == len(arr):
print("All elements are unique in the numpy array")
else:
print("All elements are not unique in the numpy array")
```

Output

```All elements are unique in the numpy array

```

## Summary

We learned about two different ways, to check if a NumPy Array has only unique elements or not in Python. Thanks.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top