Find element in Array - Python
Last Updated :
28 Nov, 2024
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.
Python
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")
Let's take a look at methods of finding an item in an array:
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.
Python
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")
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.
Python
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")
Outputfound 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.
Python
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)
The filter() function filters out all elements in the array that satisfy the given condition (in this case, even numbers).
Similar Reads
Find Index of Element in Array - Python In Python, arrays are used to store multiple values in a single variable, similar to lists but they offer a more compact and efficient way to store data when we need to handle homogeneous data types . While lists are flexible, arrays are ideal when we want better memory efficiency or need to perform
2 min read
Find index of element in array in python We often need to find the position or index of an element in an array (or list). We can use an index() method or a simple for loop to accomplish this task. index() method is the simplest way to find the index of an element in an array. It returns the index of the first occurrence of the element we a
2 min read
Search Elements in a Matrix - Python The task of searching for elements in a matrix in Python involves checking if a specific value exists within a 2D list or array. The goal is to efficiently determine whether the desired element is present in any row or column of the matrix. For example, given a matrix a = [[4, 5, 6], [10, 2, 13], [1
3 min read
Find an Element In a List of Tuples In Python programming, it is often necessary to locate an element inside a list of tuples. Tuples are arranged collections, and locating a particular piece inside them requires knowledge of a variety of strategies. When data is kept as tuples inside a list, this procedure is essential for data retri
3 min read
Python Program to Find closest number in array Given an array of sorted integers. We need to find the closest value to the given number. Array may contain duplicate values and negative numbers. Examples: Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9} Target number = 11 Output : 9 9 is closest to 11 in given array Input :arr[] = {2, 5, 6, 7, 8, 8, 9};
4 min read