A common problem in Python is finding out where a specific item is in a list. There are a few ways to do that.
To know where in a Python list a specific item is you can use the list index() method that returns the index of the item if the item is in the list. Otherwise, it raises a ValueError exception. Another way to find the position of an item in a list is by using the linear search algorithm.
Knowing where an element is in a list means finding the index of that element in the list. That’s because elements in a Python list are accessed based on their index.
In this tutorial, we will use the terms item in a list, and element in a list interchangeably.
Let’s learn more about this!
How Do You Find the Index of an Item of a List in Python?
Let’s say you know a list contains a particular item. How can you find its index in the list?
Python lists provide the index() method that returns the index of an item in the list. The index() method raises a ValueError exception if the item is not in the list.
Let me show you how it works…
fruits = ['orange', 'apple', 'banana']
print(fruits.index('orange'))
[output]
0
The index() method returns 0 because that’s the index of the string we are looking for inside the list.
Note: Remember that the value of the first index in a Python list is zero.
We have seen what happens when the element exists in the list. Here is what happens if the string we look for doesn’t exist in the list:
print(fruits.index('pineapple'))
This time the Python interpreter raises a ValueError exception because the string we are searching doesn’t exist in the list.
Traceback (most recent call last):
File "where_in_list.py", line 4, in <module>
print(fruits.index('pineapple'))
ValueError: 'pineapple' is not in list
Makes sense?
Let’s continue…
Using Linear Search to Get the Index of a List Item Using Python
Another way to find where an item is in a list is by using linear search.
With linear search, you start at the beginning of the list (index zero) and you keep increasing the index until you find an item that matches the value you are looking for.
Let me explain this to you with some Python code…
def linear_search(search_value, values):
for i in range(len(values)):
if values[i] == search_value:
return i
return -1
fruits = ['orange', 'apple', 'banana']
We have defined a Python function called linear_search() that takes two arguments: the value to search for and the list in which we are searching.
Using the range() and len() functions we go through every item in the list starting from the index zero and we verify if any item matches the value we are looking for. The len() function returns the list length.
If we find an item that matches what we are searching for we return the index of that item. Otherwise, we return -1.
Here are a few examples of execution:
print(linear_search('orange', fruits))
[output]
0
The function has found the string ‘orange’ at index zero.
print(linear_search('pineapple', fruits))
[output]
-1
This time the algorithm has not found the string ‘pineapple’ in the list and it returns -1.
Using Linear Search and Enumerate to Find the Index of a List Element in Python
Here is something useful to know…
We can simplify the definition of the linear_search() function we have created before. To do that we can use the Python enumerate function.
In the previous implementation of the linear search, we generated indexes in the for loop using the range and len functions.
Let’s see how we can do that with the enumerate function instead.
def linear_search(search_value, values):
for index, value in enumerate(values):
if value == search_value:
return index
return -1
Can you see how much cleaner is the code?
There are definitely a lot fewer brackets that usually make code harder to read.
Run this on your machine and confirm it works in the same way as the code without enumerate.
Here is how this for loop works with enumerate…
At every iteration, the enumerate function returns the index and value for each item in the list. In this way, we don’t have to manually generate the index the way we have done before.
Here is what you get when you pass our list to the enumerate function.
print(enumerate(fruits))
[output]
<enumerate object at 0x102e292c0>
You get back an enumerate object. To see something more useful we have to convert this object into a list.
print(list(enumerate(fruits)))
[output]
[(0, 'orange'), (1, 'apple'), (2, 'banana')]
Can you see now how the for loop can access the index and value for items in the list while iterating through the list?
How to Find Where an Item is in a Python List If It Appears Multiple Times
And what happens if the item you are looking for has duplicates in the list?
First of all, let’s see if we can find duplicate items in a list using the index() method.
Update the list so that the string ‘orange’ appears twice and then retrieve the index of ‘orange’ from the list.
fruits = ['orange', 'apple', 'banana', 'orange']
print(fruits.index('orange'))
[output]
0
The result doesn’t change compared to the scenario in which the string ‘orange’ only appeared once in the list.
The list index() method only returns the index of the first occurrence of a specific item in a list.
Is there a way to get back both indexes?
We would like to get back 0 and 3 in this example.
Let’s update the linear search function to return a list of indexes in case the value we are looking for is in the list one or more times.
Otherwise, we return -1 as already done before.
def linear_search(search_value, values):
found_indexes = []
for index, value in enumerate(values):
if value == search_value:
found_indexes.append(index)
if len(found_indexes) > 0:
return found_indexes
else:
return -1
We have applied the following code changes:
- Define an empty list found_indexes that will contain the list of indexes in case an item is found in the list.
- Append each index identified to the found_indexes list.
- Return the found_indexes list if it’s not empty. Otherwise, return -1.
It’s time to test this code:
fruits = ['orange', 'apple', 'banana', 'orange']
print(linear_search('orange', fruits))
[output]
[0, 3]
print(linear_search('pineapple', fruits))
[output]
-1
Nice!
We got back the expected results.
Conclusion
Lists are one of the main data types in Python.
We have covered a few ways to get the index of an element in a list and while doing that we have used several Python constructs:
- List index() method
- Linear search algorithm
- For loops
- Custom functions
- Enumerate function
And now it’s your turn to use what you learned!
Related article: Practice the use of list methods and keep improving your Python programs!
Claudio Sabato is an IT expert with over 15 years of professional experience in Python programming, Linux Systems Administration, Bash programming, and IT Systems Design. He is a professional certified by the Linux Professional Institute.
With a Master’s degree in Computer Science, he has a strong foundation in Software Engineering and a passion for robotics with Raspberry Pi.