0
0
NumPydata~5 mins

np.setdiff1d() for difference in NumPy

Choose your learning style9 modes available
Introduction

We use np.setdiff1d() to find items that are in one list but not in another. It helps us see what is unique to the first list.

You want to find which products a customer bought that are not in the store's current stock.
You have two lists of email addresses and want to find which emails are new.
You want to compare two sets of survey answers and find which answers appear only in the first set.
You want to find which students attended the first class but missed the second.
Syntax
NumPy
np.setdiff1d(array1, array2, assume_unique=False)

array1 and array2 are the two arrays you compare.

The function returns sorted unique values in array1 that are not in array2.

Examples
This finds values in arr1 that are not in arr2. Output will be [1 2].
NumPy
import numpy as np

arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([3, 4, 5])
diff = np.setdiff1d(arr1, arr2)
print(diff)
Works with strings too. Finds fruits in arr1 not in arr2.
NumPy
import numpy as np

arr1 = np.array(['apple', 'banana', 'cherry'])
arr2 = np.array(['banana', 'date'])
diff = np.setdiff1d(arr1, arr2)
print(diff)
Sample Program

This program finds numbers that are in list_a but missing from list_b. It prints those unique numbers.

NumPy
import numpy as np

# Two lists of numbers
list_a = np.array([10, 20, 30, 40, 50])
list_b = np.array([30, 40, 60])

# Find items in list_a not in list_b
unique_to_a = np.setdiff1d(list_a, list_b)

print("Items in list_a but not in list_b:", unique_to_a)
OutputSuccess
Important Notes

The result is always sorted and contains unique values only.

If you know your arrays have unique values already, set assume_unique=True for faster results.

Summary

np.setdiff1d() helps find what is unique to the first array compared to the second.

It works with numbers, strings, or any comparable data.

The output is sorted and contains no duplicates.