How to Check Array Contains an Element in Python

Python does not have built-in support for Arrays, but you can create or use the arrays using the numpy library.

Python Array Contains

Use the in operator to check if an array contains an element in Python. The in operator checks whether a specified element is an integral element of a sequence like string, array, list, tuple, etc.

To work with the numpy library, you must install numpy in your Python environment. Then import the library using the import statement.

import numpy as np

To create an array in Python, use the np.array() method.

arr = np.array([11, 19, 21])

Use the in operator to check if the array contains a “19” element.

import numpy as np

arr = np.array([11, 19, 21])

element_exist = 19 in arr

print(element_exist)

Output

True

That means the array contains the “19” element, which is True because it is in the array.

Let me demonstrate an example where the array does not contain the provided element.

import numpy as np

arr = np.array([11, 19, 21])

element_exist = 18 in arr

print(element_exist)

Output

False

That is it for if an array contains an element in Python.

Related posts

Python array length

Python array append

Python print array

Python initialize array

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.