When working with Python lists, you may need to find out the index at which a particular item occurs. You can do this by:
Looping through the list and checking if the item at the current index is equal to the particular value Using the built-in list method index()
You’ll learn both of the above in this tutorial. Let’s get started.👩🏽💻
Python Lists, Revisited
In Python, a list is a collection of items—of the same or different data types. They are mutable; you can modify them in place without having to create a new list. Consider this example fruits: a list of 5 different fruits. You can get the length of any Python object by using the built-in len() function. So you can call the len() function with the list object (fruits) as the argument to get its length, as shown below. We’ll use the fruits list as a running example in this tutorial.
Indexing in Python Lists
Python follows zero indexing. So in any Python iterable, the first item is at index 0, the second item is at index 1, and so on. If the length of the iterable is k, then the last item is at the index k - 1. In Python, you can use the range() function to get indices as you loop through iterables. The following code cell explains this. Now that we have covered the basics of Python lists let’s learn how to find the index of an item in a list.
Find Index of a List Item by Iteration Using for Loops
Let’s consider the list fruits from the previous section. We’ll learn how to find the index of a specific item in this list by iteration using for loop.
Using for Loop and range() Function
Let’s fix target: the value we are searching for in the list. You can use for loop and range() function to get the list of indices from 0 to len(fruits) - 1.
Loop through the list of fruits accessing each index.
Check if the item at the current index i is equal to the target.
If True, print out that the target has been found at the index i.
In this example, the target string ‘mango’ appears exactly once (at index 1) in the list fruits. However, sometimes the target value appears more than once or does not appear at all. To handle these cases, let’s modify the above looping and wrap the contents inside a function called find_in_list.
Understanding the Function Definition
The function find_in_list has two parameters:
target: the value you are searching for, andpy_list: the Python list that you are searching through.
In the function body, we initialize an empty list target_indices. We loop through the list and access the list items. If the target has been found at a particular index, we add that index to the target_indices list using the append() method.
If the target is never found, then target_indices is an empty list; the user is notified that the target is not present in the list.If the target is found at more than one index, then target_indices contains all those indices.
Next, let’s redefine the fruits list as shown. This time we are searching for the target string ‘mango’, which occurs twice—at indices 1 and 4. On calling the function find_in_list with target and fruits as the arguments, we see that both the indices are returned. If you try searching for ’turnip’ which is not present in the fruits list, you get a message that the target has not been found.
Using for Loop and enumerate() Function
In Python, you can use the enumerate() function to access both the index and the items simultaneously—without having to use the range() function. The following code cell shows how you can use the enumerate() function to get both the indices and the items. Now, let’s rewrite the Python function to find the index of items in the list using enumerate() function. As with the previous section, you can now call the find_in_list function with valid arguments. You can translate the above function definition into an equivalent list comprehension and we’ll do that in the next section.
Find Index of a List Item by Iteration Using List Comprehension
List comprehensions in Python allow you to create lists from existing lists based on some condition. Here’s the general construct: The figure below describes how to identify the elements of list comprehension; using this, you can convert the function find_in_list to a list comprehension. Using the above, the expression for list comprehension to create target indices is as follows. As an exercise, you can try running the above code snippet for a few other examples.
Find Index of a List Item Using the index() Method
To find the index of an item in a Python list, you can also use the built-in .index() method. Here is the general syntax: Parsing the above method:
value is the target value that you are searching for.start and end are optional positional arguments; you can use them to search find the index of an item in the list slice starting at start and extending up to end - 1.
Let’s revisit our example to understand how the .index() method works. Even though there are two occurrences of ‘mango’ in the fruits list, you can see that only the index of the first occurrence has been returned. To get the index of the second occurrence of mango, we can search through the list slice starting at index 2 and extending up to index 5, as shown below.
How to Handle ValueErrors in Python
Now let’s see what happens if you try to find the index of an item that is not present in the list, say, ‘carrot’. As seen in the code cell above, this throws a ValueError. In Python, you can handle this as an exception using the try and except blocks. The general syntax to use try-except is as follows. Using the above try-except blocks, we can handle ValueError as an exception. The above code does the following:
If the target is present in the list, it returns the index of the target.If the target is not present, it handles ValueError as an exception and prints out the error message.
Summing Up
Here’s a summary of the different methods you have learned to find the index of an item in a Python list.
You can use Python’s for loop and range() function to get the items and their respective indices. Check if the items at the indices match the target.You can also use the enumerate() function to simultaneously access the item and the index. You may use both the above methods inside of a list comprehension expression.To find an item’s index in a list, you can also use the built-in .index() method.list.index(value) returns the index of the first occurrence of value in list. If the value is not present, it raises a ValueError.You can search through a certain slice of the list using list.index(value, start, end) to search for the occurrence of a value in the list slice [start:end-1].
Next, learn to sort a Python dictionary by key or by value. Happy Python programming!