Tags
python
Asked 3 years ago
13 Aug 2021
Views 481
Adrien

Adrien posted

Check element exists in array - in Python

Check element exists in array - in Python
sandip

sandip
answered May 2 '23 00:00

in Python , you can use the in operator or the index() method to check if an element exists in an array.

Using the in operator :


arr = [1, 2, 3, 4, 5]
element = 3

if element in arr:
    print("Element exists in array")
else:
    print("Element does not exist in array")

This code creates an array arr and an element element, and then checks if the element exists in the array using the in operator. If the element is present in the array, it prints "Element exists in array", otherwise it prints "Element does not exist in array".

Using the index() method:


arr = [1, 2, 3, 4, 5]
element = 3 
try:
    index = arr.index(element)
    print("Element exists in array at index", index)
except ValueError:
    print("Element does not exist in array")

This code creates an array arr and an element element, and then tries to find the index of the element using the index() method. If the element is present in the array, it prints "Element exists in array at index" followed by the index of the element, otherwise it prints "Element does not exist in array". If the element is not found in the array, the index() method raises a ValueError exception, which is caught using a try...except block.

Both of these methods are efficient and reliable ways to check if an element exists in an array in Python.
Post Answer