In this guide, you’ll learn how to find the index of an element in a Python list, both using simple iterations and a built-in list method index().

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.

fruits = ["apple","mango","strawberry","pomegranate","melon"]

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.

len(fruits)
# Output: 5

 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.

Note: When you loop through range(k), you get the indices 0,1,2,…,(k-1). So by setting k = len(list), you can get the list of all valid indices.

The following code cell explains this.

for i in range(len(fruits)):
  print(f"i:{i}, fruit[{i}] is {fruits[i]}")

# Output
i:0, fruit[0] is apple
i:1, fruit[1] is mango
i:2, fruit[2] is strawberry
i:3, fruit[3] is pomegranate
i:4, fruit[4] is melon

Now that we have covered the basics of Python lists let’s learn how to find the index of an item in a list.

<img alt="python-find-in-list" data- data-src="https://kirelos.com/wp-content/uploads/2022/06/echo/find-index-of-in-list…-1500×844.png" data- src="data:image/svg xml,” width=”900″>

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.
fruits = ["apple","mango","strawberry","pomegranate","melon"]

target = "mango"

for i in range(len(fruits)):
  if fruits[i] == target:
   print(f"{target} found at index {i}")

# Output
mango found at index 1

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, and
  • py_list: the Python list that you are searching through.
def find_in_list(target,py_list):
  target_indices = []
  for i in range(len(fruits)):
    if fruits[i] == target:
      target_indices.append(i)  
  if target_indices == []:
    print("Sorry, target not found!")
  else:
    print(f"{target} is found at indices {target_indices}")

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.

Note: In Python, list.append(item) adds item to the end of list.

  • 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.

fruits = ["apple","mango","strawberry","pomegranate","mango","melon"]
target = "mango"
find_in_list(target,fruits)

# Output
mango is found at indices [1, 4]

On calling the function find_in_list with target and fruits as the arguments, we see that both the indices are returned.

target = "turnip"
find_in_list(target,fruits)

# Output
Sorry, target not found!

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.

fruits = ["apple","mango","strawberry","pomegranate","mango","melon"]
for index,fruit in enumerate(fruits):
  print(f"Index {index}: {fruit}")

# Output
Index 0: apple
Index 1: mango
Index 2: strawberry
Index 3: pomegranate
Index 4: mango
Index 5: melon

Now, let’s rewrite the Python function to find the index of items in the list using enumerate() function.

def find_in_list(target,py_list):
  target_indices = []
  for index, fruit in enumerate(fruits):
   if fruit == target:
    target_indices.append(index) 
  if target_indices == []:
    print("Sorry, target not found!")
  else:
    print(f"{target} is found at indices {target_indices}")

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:

new_list = [ for  if ] 

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.

<img alt="python-find-in-list" data- data-src="https://kirelos.com/wp-content/uploads/2022/06/echo/list-comp-exp.png" data- src="data:image/svg xml,” width=”900″>

Using the above, the expression for list comprehension to create target indices is as follows.

target_indices = [index for index,fruit in enumerate(fruits) if fruit==target]

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:

list.index(value,start,end)

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.

Note: The .index() method returns only the index of the first occurrence of value in list. Even when you find index of an item in a list slice [start: end-1], this method returns only the index corresponding to the first occurrence of the item.

Let’s revisit our example to understand how the .index() method works.

fruits = ["apple","mango","strawberry","pomegranate","mango","melon"]
target = "mango"

fruits.index(target)
1

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.

fruits.index(target,2,5)
4

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'.

target = "carrot"

fruits.index(target)

# Output
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
 in ()
      1 target = "carrot"
      2 
----> 3 fruits.index(target)

ValueError: 'carrot' is not in list

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.

try:
  # to do this
except :
  # do this to handle  as exception

Using the above try-except blocks, we can handle ValueError as an exception.

target = "carrot"
try:
  fruits.index(target)
except ValueError:
  print(f"Sorry, could not find {target} in list")

# Output
Sorry, could not find carrot in list

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!