Find element in Array - Python
Finding an item in an array in Python can be done using several different methods depending on the situation. Here are a few of the most common ways to find an item in a Python array.
Using the in Operator
in operator is one of the most straightforward ways to check if an item exists in an array. It returns True if the item is present and False if it's not.
import array
# Create an array of integers
arr = array.array('i', [1, 2, 3, 4, 5])
# Check if an item exists in the array
val = 3
if val in arr:
print("Item found")
else:
print(f"Not found")
Output
Item found
Let's take a look at methods of finding an item in an array:
Table of Content
Using index() Method
If we want to find the index of an item in the array, we can use the index() method. This method returns the index of the first occurrence of the item in the array. If the item is not found, it raises a ValueError.
import array
# Create an array of integers
arr = array.array('i', [1, 2, 3, 4, 5])
# Find the index of an item
try:
val = 4
idx = arr.index(val)
print(f"found at index {idx}.")
except ValueError:
print("not found")
Output
found at index 3.
Note: index() is useful if you also want the index of the item, but it raises an error if the item is not found.
Using a Loop for Custom Searching
If we need to perform more complex search operations such as checking for multiple occurrences or applying custom logic, we can loop through the array manually.
import array
# Create an array of integers
arr = array.array('i', [1, 2, 3, 4, 5, 3])
# Find all occurrences of an item
val = 3
idx = []
for i in range(len(arr)):
if arr[i] == val:
idx.append(i)
if idx:
print(f"found at indices: {idx}.")
else:
print("not found")
Output
found at indices: [2, 5].
This approach can be modified to handle more complex search requirements (e.g., partial matches, case-insensitive searches).
Using filter() Function for Advanced Filtering
If you want to filter items based on certain criteria, you can use filter() function in combination with a lambda function.
import array
# Create an array of integers
arr = array.array('i', [1, 2, 3, 4, 5, 6, 7])
# Find all even numbers using filter
li = list(filter(lambda x: x % 2 == 0, arr))
print(li)
Output
[2, 4, 6]
The filter() function filters out all elements in the array that satisfy the given condition (in this case, even numbers).