Finding an item in an array inPython 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 aPython 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.
Pythonimportarray# Create an array of integersarr=array.array('i',[1,2,3,4,5])# Check if an item exists in the arrayval=3ifvalinarr: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.
Pythonimportarray# Create an array of integersarr=array.array('i',[1,2,3,4,5])# Find the index of an itemtry:val=4idx=arr.index(val)print(f"found at index{idx}.")exceptValueError: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.
Pythonimportarray# Create an array of integersarr=array.array('i',[1,2,3,4,5,3])# Find all occurrences of an itemval=3idx=[]foriinrange(len(arr)):ifarr[i]==val:idx.append(i)ifidx: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 usefilter() function in combination with a lambda function.
Pythonimportarray# Create an array of integersarr=array.array('i',[1,2,3,4,5,6,7])# Find all even numbers using filterli=list(filter(lambdax: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).