Here are six ways to check if an array contains an element in Python.
- Using the “in” operator
- Using “for loop”
- Using the “not in” operator
- Using the “lambda” function
- Using “any()” function
- Using “count()” function
Method 1: Using the “in” operator
To check if an array contains an element in Python, you can use the “in” operator. The in operator checks whether a specified element is an integral sequence element like an array, list, tuple, etc.
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
Method 2: Using for loop
cars = ['mercedez', 'bmw', 'ferrari', 'audi']
for car in cars:
if car == 'bmw':
print('It exists!')
Output
It exists!
Method 3: Using not in operator
cars = ['mercedez', 'bmw', 'ferrari', 'audi']
if 'bmw' not in cars:
print('It exists!')
else:
print("Does not exist!")
Output
Does not exist!
Method 4: Using the lambda function
cars = ['mercedez', 'bmw', 'ferrari', 'audi']
element = list(filter(lambda x: 'mercedez' in x, cars))
print(element)
Output
['mercedez']
Method 5: Using any() function
cars = ['mercedez', 'bmw', 'ferrari', 'audi']
if any(element in 'audi' for element in cars):
print('It exists')
Output
It exists
Method 6: Using the count() method
cars = ['mercedez', 'bmw', 'ferrari', 'audi']
if cars.count('bmw') > 0:
print("It exists!")
Output
It exists!
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.