~2 min read • Updated Sep 17, 2025
Program Overview
This Python program uses the NumPy library to create two arrays.
It then extracts and displays the following elements using NumPy functions:
- Duplicate elements
- Unique (non-repeating) elements
- Common elements between the two arrays
Python Code:
import numpy as np
# Create two sample arrays
array1 = np.array([1, 2, 3, 4, 5, 6, 2, 3])
array2 = np.array([3, 4, 7, 8, 3, 9, 10])
# Common elements between both arrays
common = np.intersect1d(array1, array2)
# Unique elements in each array
unique1 = np.setdiff1d(array1, array2)
unique2 = np.setdiff1d(array2, array1)
# Duplicate elements in each array
duplicates1 = np.unique(array1[np.isin(array1, array1[np.where(np.bincount(array1) > 1)])])
duplicates2 = np.unique(array2[np.isin(array2, array2[np.where(np.bincount(array2) > 1)])])
print("Array 1:", array1)
print("Array 2:", array2)
print("Common elements:", common)
print("Unique elements in Array 1:", unique1)
print("Unique elements in Array 2:", unique2)
print("Duplicate elements in Array 1:", duplicates1)
print("Duplicate elements in Array 2:", duplicates2)
Sample Output:
Array 1: [1 2 3 4 5 6 2 3]
Array 2: [3 4 7 8 3 9 10]
Common elements: [3 4]
Unique elements in Array 1: [1 2 5 6]
Unique elements in Array 2: [ 7 8 9 10]
Duplicate elements in Array 1: [2 3]
Duplicate elements in Array 2: [3]
Explanation:
- np.intersect1d() finds common elements between the two arrays
- np.setdiff1d() extracts elements that are unique to each array
- np.bincount() and np.where() help identify repeated values
- np.unique() ensures that duplicates are listed only once
Written & researched by Dr. Shahin Siami