- Python: check if item or value exists in list or array
- Check if the element exists
- Obtain element index
- python find in array
- Find multiple occurences
- Find in string arrays
- Find in numeric array
- Find the Index of an Element in a List in Python
- Use the List index() Method to Find the Index of a List in Python
- Use numpy.where() to Find the Index of a List in Python
- Related Article — Python List
Python: check if item or value exists in list or array
Sometimes we need to know if an element or value is within a list or array in Python.
There may be a need to simply know if it exists, but it is also possible that we need to obtain the position of an element, that is, its index.
Today we will see how to do it in Python, to check if an element exists in array, as well as to obtain the index of a certain value.
Check if the element exists
We use the operator in , which returns a Boolean indicating the existence of the value within the array. This way:
As we can see, it does not matter if our array or list is string or integer type. Of course, they must be primitive data.
Obtain element index
If we want to obtain the index or position, we use the index method of the lists. This way:
When we run it, it prints position 1 (remember that the values in the list start at 0). It is important to remember that an error will be generated if the element does not exist in the list. To handle it, we can do something like this:
In that case, an exception is generated; because the element does not exist in the list.
I am available for hiring if you need help! I can help you with your project or homework feel free to contact me.
If you liked the post, show your appreciation by sharing it, or making a donation
python find in array
Arrays are usually referred to as lists. For convience, lets call them arrays in this article.
Python has a method to search for an element in an array, known as index().
We can find an index using:
Arrays start with the index zero (0) in Python:
If you would run x.index(‘p’) you would get zero as output (first index).
Array duplicates: If the array contains duplicates, the index() method will only return the first element.
Find multiple occurences
If you want multiple to find multiple occurrences of an element, use the lambda function below.
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
Find in string arrays
To find an element in a string array use:
x = [«Moon»,«Earth»,«Jupiter»]
print(x.index(«Earth»))
You could use this code if you want to find multiple occurrences:
x = [«Moon»,«Earth»,«Jupiter»,«Neptune»,«Earth»,«Venus»]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes(«Earth»,x))
Find in numeric array
The index method works on numeric arrays too:
To find multiple occurrences you can use this lambda function:
x = [5,1,7,0,3,4,5,3,2,6,7,3,6]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes(7,x))
Find the Index of an Element in a List in Python
- Use the List index() Method to Find the Index of a List in Python
- Use numpy.where() to Find the Index of a List in Python
This tutorial will demonstrate how to find the position or index of an element in a Python list.
Use the List index() Method to Find the Index of a List in Python
Python list has a built-in method called index() , which accepts a single parameter representing the value to search within the existing list. The function returns the index of the first occurrence that it finds starting from index 0 regardless of how many times it occurs within the list.
For example, declare a list with a repeating value of 20 and call the function index(20) and print what it returns.
lst = [13, 4, 20, 15, 6, 20, 20] print(lst.index(20))
The first occurrence of the value 20 found within the lst array was on index 2 , which is the result of the function call. The other elements with the same value are ignored since it already has found a match within the list.
What happens when a value does not exist within the given list, and we call index() passing the non-existent value? Let’s take this for example.
lst = [13, 4, 20, 15, 6, 20, 20] print (lst.index(21))
ValueError: 21 is not in list
The function will throw an error if the index isn’t found within the list. In some cases, this might be unfavorable to invoke an error. To avoid this, catch the error with a try. except block and make it so that if the index does not exist within the list, assign it as -1 .
lst = [13, 4, 20, 15, 6, 20, 20] try: ndx = lst.index(21) except: ndx = -1 print (ndx)
This way, an explicit error won’t have to be invoked, and the program can continue running after the operation.
Use numpy.where() to Find the Index of a List in Python
The NumPy module has a pre-defined function called where() which deals with locating multiple items within a list and accepts a condition.
In this case, we will exclusively use where() to locate a given value’s indices. Unlike the built-in index() function, the where() function can return a list of indices where the value is located if it exists more than once within a list. This is useful if you need all the occurrences of the value instead of just the first occurrence.
The first step is to convert a Python list into a NumPy array. To do this, call the function np.array() .
import numpy as np lst = np.array(lst = [13, 4, 20, 15, 6, 20, 20])
After initializing the NumPy array, we only need to fill the first parameter of where() . Initialize the first parameter as lst == 20 to locate the given list’s indices with the value 20 .
import numpy as np lst = [13, 4, 20, 15, 6, 20, 20] lst = np.array(lst) result = np.where(lst == 20) print(result)
Since NumPy mainly deals with matrices, the where() function returns a tuple of arrays instead of just a single list. If outputting only the single list is preferred, then call the first index of the result and output it using print() .
import numpy as np lst = [13, 4, 20, 15, 6, 20, 20] lst = np.array(lst) result = np.where(lst == 20) print(result[0])
Note that NumPy arrays are delimited by single whitespace instead of the normal commas.
In summary, the index() function is the easiest way to find the position of an element within a Python list. Although, this function only returns the index of the first occurrence of the given value.
To return multiple indices if multiple instances of the value exist, then you can opt to use the where() function in the NumPy module.
Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.