w3resource

NumPy: Find the set exclusive-or of two arrays


Set Exclusive-Or of Arrays

Write a NumPy program to find the set exclusive-or of two arrays. Set exclusive-or will return sorted, distinct values in only one (not both) of the input arrays.

Pictorial Presentation:

Python NumPy: Find the set exclusive-or of two arrays

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array 'array1'
array1 = np.array([0, 10, 20, 40, 60, 80])

# Printing the contents of 'array1'
print("Array1: ", array1)

# Creating a Python list 'array2'
array2 = [10, 30, 40, 50, 70]

# Printing the contents of 'array2'
print("Array2: ", array2)

# Finding and printing the unique values that are in only one (not both) of the input arrays
print("Unique values that are in only one (not both) of the input arrays:")
print(np.setxor1d(array1, array2)) 

Sample Output:

Array1:  [ 0 10 20 40 60 80]                                           
Array2:  [10, 30, 40, 50, 70]                                          
Unique values that are in only one (not both) of the input arrays:     
[ 0 20 30 50 60 70 80]

Explanation:

In the above code -

array1 = np.array([0, 10, 20, 40, 60, 80]): Creates a NumPy array with elements 0, 10, 20, 40, 60, and 80.

array2 = [10, 30, 40, 50, 70]: Creates a Python list with elements 10, 30, 40, 50, and 70.

print(np.setxor1d(array1, array2)): The np.setxor1d function returns the sorted symmetric difference between the two input arrays, which consists of elements that are in either ‘array1’ or ‘array2’ but not in both. In this case, the symmetric difference is [0, 20, 30, 50, 60, 70, 80], so the output will be [ 0 20 30 50 60 70 80].


For more Practice: Solve these Related Problems:

  • Calculate the symmetric difference between two arrays using np.setxor1d and verify that only unique elements remain.
  • Create a function that returns elements present in only one of the two input arrays.
  • Handle cases where one array is entirely a subset of the other and validate the exclusive-or result.
  • Compare the output of symmetric difference with manual set operations in Python.

Go to:


PREV : Set Difference of Arrays
NEXT : Union of Two Arrays


Python-Numpy Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.