How to Check If Array Contains an Element in Python

Here are six ways to check if an array contains an element in Python.

  1. Using the “in” operator
  2. Using “for loop”
  3. Using the “not in” operator
  4. Using the “lambda” function
  5. Using “any()” function
  6. 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

Python array length

Python print array

Python initialize array

Leave a Comment

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