The most efficient way to check whether a numpy array contains a specific element in Python is to use either the in operator or np.isin().any() method.
Method 1: Using the in operator
The in operator checks whether a specified element exists in the array or list. It is primarily used for lists, but you can use it in an array. However, it internally converts an array to a list, so avoid for extensive data (O(n) time, non-vectorized).
import numpy as np arr = np.array([11, 13, 15, 17, 19]) element_exist = 19 in arr print(element_exist) # Output: True
In this code, element 19 exists in the numpy array, so the “in” operator returns True.
Let me demonstrate an example where the array does not contain the provided element.
import numpy as np arr = np.array([11, 13, 15, 17, 19]) element_exist = 16 in arr print(element_exist) # Output: False
ND (2D) array
What if the input is a 2D array? In that case, we need to flatten it first using the np.flatten() method, then check the element.
import numpy as np arr = np.array([[1, 2], [3, 4]]) element = 2 contains = element in arr.flatten() # Flatten for ND print(contains) # Output: True
Method 2: Using np.isin().any() Method
The np.isin(arr, element).any() is a membership method that will test whether a single or multiple elements exist in the input array. If they exist, it returns True; otherwise, it returns False.
The np.isin() method checks whether the given value is in the specified array. Then, we chained with the np.any() method, which returns a boolean value (True or False).
import numpy as np arr = np.array([11, 13, 15, 17, 19]) element = 19 element_exist = np.isin(arr, element).any() print(element_exist) # Output: True
In this code, we checked for a single element “19”. Since it exists, it returns True.
Multiple elements, any match
What if we are checking an array against an array? Meaning what if we have an array of values that needs to be checked against an input array? In that case, even if a single element in the checking array matches an element in the input array, it returns True. If no element matches, it returns False.
import numpy as np input_array = np.array([11, 13, 15, 17, 19]) checking_array = [19, 46] element_exist = np.isin(arr, elements).any() print(element_exist) # Output: True
If no element in “checking_array” matches any element in “input_array”, it returns False.
import numpy as np arr = np.array([11, 13, 15, 17, 19]) elements = [10, 20, 30] elements_exist = np.isin(arr, elements).any() print(elements_exist) # Output: False
That’s all!

