How to Get the Index of an Element in a List in Python?

Recently, one of my team members was required to get the index of an element in a Python list. I suggested a few methods. In this tutorial, I will show you how to get the index of an element in a list in Python with examples.

To get the index of an element in a list in Python, you can use the built-in index() method. This method returns the index of the first occurrence of the specified element. For example, if you have a list cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"] and you want to find the index of “Chicago”, you can use index_chicago = cities.index("Chicago"), which will return 2.

1. Using the index() Method

The best and most recommended way to find the index of an element in a list in Python is by using the index() method. This built-in method returns the index of the first occurrence of the specified element.

Syntax

list.index(element)

Example

Let me show you an example of it.

Suppose we have a list of popular cities in the USA:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

To find the index of “Chicago”:

index_chicago = cities.index("Chicago")
print(index_chicago)  # Output: 2

The index() method searches the list for “Chicago” and returns its position, which is 2.

I executed the above Python code, and you can see the output in the screenshot below:

get index of element in list python

Handling Errors

If the element is not found, the index() method raises a ValueError. To handle this, you can use a try-except block. Here is the complete Python code.

try:
    index_boston = cities.index("Boston")
except ValueError:
    index_boston = -1  # Or any other value that indicates "not found"
print(index_boston)  # Output: -1

Check out How to Unpack List in Python

2. Using a Loop

Sometimes, you might want to find all occurrences of an element in the Python list. For this, you can use a loop:

Example

Consider a list of student names, where some names might repeat:

students = ["John", "Emma", "Olivia", "John", "Michael", "Emma"]

To find all indices of “Emma”:

indices = [i for i, name in enumerate(students) if name == "Emma"]
print(indices)  # Output: [1, 5]

This list comprehension iterates over the list and collects the indices where the name is “Emma”.

Here is the output you can see in the screenshot below:

find index of element in list python

Check out How to Sum Elements in a List in Python

3. Using numpy for Large Lists

If you’re working with large lists and need a more efficient solution, consider using the numpy library, which is optimized for numerical computations. Here is an example of finding an index of elements in a list in Python using the NumPy library.

Example

First, install numpy if you haven’t already:

pip install numpy

Then, use it to find the index:

import numpy as np

students = np.array(["John", "Emma", "Olivia", "John", "Michael", "Emma"])
indices = np.where(students == "Emma")[0]
print(indices)  # Output: [1 5]

The np.where function returns an array of indices where the condition is true.

I executed the above Python code, and you can see the output in the screenshot below:

python get index of element in list

4. Using pandas for DataFrames

If your data is structured in a DataFrame, pandas provides convenient methods to find indices. Let me show you an example to get index of item in list in Python using Pandas.

Example

First, install pandas if you haven’t already:

pip install pandas

Then, use it to find the index:

import pandas as pd

data = {"Name": ["John", "Emma", "Olivia", "John", "Michael", "Emma"]}
df = pd.DataFrame(data)

indices = df.index[df["Name"] == "Emma"].tolist()
print(indices)  # Output: [1, 5]

The df.index method returns the indices where the condition is met.

Conclusion

There are multiple ways to get the index of the elements in a list in Python. The index() method is perfect for most cases, and I personally recommend that approach. For large datasets, libraries like numpy and pandas provide efficient solutions. I hope these real-time examples will help you.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.