Home »
Python »
Python Programs
Python NumPy - Find the XOR elements of two arrays
By IncludeHelp Last updated : January 2, 2024
Problem statement
Given two NumPy arrays, write a Python program to find the XOR elements of two NumPy arrays.
Finding the XOR elements of two NumPy arrays
For this purpose, use the following steps:
- Input two NumPy arrays (arr1 and arr2).
- Find the unique elements of arr1 which are not present in arr2. Store the result in a variable out1.
- Find the unique elements that are not present in either array with respect to both of the arrays using the numpy.setdiff1d(), then concatenate them using the numpy.concatenate() method, and then sort the elements using the numpy.sort() method. Store the result in a variable out2.
- Now, use the assert numpy.allclose(out1, out2) method. The numpy.allclose() method returns True if two arrays are element-wise equal within a tolerance.
- Now, print the out1 which contains the result.
Let us understand with an example.
Python code to find the XOR elements of two NumPy arrays
# Import NumPy module
import numpy as np
# Creating two NumPy arrays
arr1 = np.array([50, 100, 200, 500, 50])
arr2 = np.array([50, 100, 400])
# Printing the arrays
print("Array 1 (arr1):\n", arr1)
print("Array 2 (arr1):\n", arr2)
# Finding the XOR elements of two
# NumPy arrays
out1 = np.setxor1d(arr1, arr2)
out2 = np.sort(np.concatenate((np.setdiff1d(arr1, arr2), np.setdiff1d(arr2, arr1))))
assert np.allclose(out1, out2)
print("The result is:\n", out1)
Output
The output of the above example is:
Array 1 (arr1):
[ 50 100 200 500 50]
Array 2 (arr1):
[ 50 100 400]
The result is:
[200 400 500]
To understand the above program, you should have the basic knowledge of the following Python topics:
Python NumPy Programs »