Python List index() with Example

โšก Smart Summary

Python list index() returns the first position of a given element, while looping constructs, list comprehensions, enumerate(), filter(), the NumPy library, and more_itertools.locate() extend this technique to collect every matching index across a list containing duplicate values.

  • ๐Ÿ”˜ index() method: The built-in index() returns the first lowest position of an element and accepts optional start and end limits.
  • โ˜‘๏ธ ValueError: index() raises a ValueError when the element is absent, so wrap the call in try-except for safe lookups.
  • โœ… All occurrences: A for-loop, while-loop, or list comprehension collects every index when a value repeats inside the list.
  • ๐Ÿงช Built-in helpers: enumerate() and filter() pair an index with each item, giving concise one-line ways to gather matching positions.
  • ๐Ÿ› ๏ธ NumPy and more_itertools: np.where() and more_itertools.locate() return all matching indexes efficiently for large datasets.
  • ๐Ÿค– AI workflows: Machine learning pipelines locate label positions and matching samples by index before arrays feed a model.

Python List index()

A list is a container that stores items of different data types (ints, floats, Boolean, strings, etc.) in an ordered sequence. It is an important data structure that is in-built in Python. The data is written inside square brackets ([]), and the values are separated by comma(,).

The items inside the list are indexed with the first element starting at index 0. You can make changes in the created list by adding new items or by updating, deleting the existing ones. It can also have duplicate items and a nested list.

There are many methods available on a list, and one of the important ones is the index().

Python List index()

The list index() method helps you to find the first lowest index of the given element. If there are duplicate elements inside the list, the first index of the element is returned. This is the easiest and straightforward way to get the index.

Besides the built-in list index() method, you can also use other ways to get the index like looping through the list, using list comprehensions, enumerate(), filter methods.

The list index() method returns the first lowest index of the given element.

Syntax

list.index(element, start, end)

Parameters

Parameters Description
element The element that you want to get the index.
start This parameter is optional. You can define the start index to search for the element. If not given, the default value is 0.
end This parameter is optional. You can specify the end index for the element to be searched. If not given, it is considered until the end of the list.

Return Value

The list index() method returns the index of the given element. If the element is not present in the list, the index() method will throw an error, for example, ValueError: ‘Element’ is not in the list.

Example: To find the index of the given element.

In the list my_list = [‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’], we would like to know the index for element C and F.

The example below shows how to get the index.

my_list = ['A', 'B', 'C', 'D', 'E', 'F']
print("The index of element C is ", my_list.index('C'))
print("The index of element F is ", my_list.index('F'))

Output:

The index of element C is  2
The index of element F is  5

Example: Using start and end in index()

In this example, we will try to limit searching for the index in a list using start and end index.

my_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
print("The index of element C is ", my_list.index('C', 1, 5))
print("The index of element F is ", my_list.index('F', 3, 7))
#using just the startindex
print("The index of element D is ", my_list.index('D', 1))

Output:

The index of element C is  2
The index of element F is  5
The index of element D is  3

Example: To test index() method with an element that is not present.

When you try to search the list for an element that is not present, you will get an error as shown below:

my_list = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
print("The index of element C is ", my_list.index('Z'))

Output:

Traceback (most recent call last):
File "display.py", line 3, in <module>
print("The index of element C is ", my_list.index('Z'))
ValueError: 'Z' is not in list

Using for-loop to get the index of an element in a list

With the list.index() method, we have seen that it gives the index of the element that is passed as an argument.

Now consider the list as: my_list = [‘Guru’, ‘Siya’, ‘Tiya’, ‘Guru’, ‘Daksh’, ‘Riya’, ‘Guru’]. The name ‘Guru’ is present 3 times in the index, and I want all the indexes with the name ‘Guru’.

Using for-loop we should be able to get the multiple indexes as shown in the example below.

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] 
all_indexes = [] 
for i in range(0, len(my_list)) : 
    if my_list[i] == 'Guru' : 
        all_indexes.append(i)
print("Originallist ", my_list)
print("Indexes for element Guru : ", all_indexes)

Output:

Originallist  ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
Indexes for element Guru :  [0, 3, 6]

Using while-loop and list.index()

Using a while-loop will loop through the list given to get all the indexes of the given element.

In the list: my_list = [‘Guru’, ‘Siya’, ‘Tiya’, ‘Guru’, ‘Daksh’, ‘Riya’, ‘Guru’], we need all the indexes of element ‘Guru’.

Below is an example that shows how to get all the indexes using a while-loop.

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] 
result = []
elementindex = -1
while True:
    try:
        elementindex = my_list.index('Guru', elementindex+1)
        result.append(elementindex)
    except  ValueError:
        break
print("OriginalList is ", my_list)
print("The index for element Guru is ", result)

Output:

OriginalList is  ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
The index for element Guru is  [0, 3, 6]

Using list comprehension to get the index of element in a list

To get all the indexes, a fast and straightforward way is to make use of list comprehension on the list.

List comprehensions are Python functions that are used for creating new sequences (such as lists, dictionaries, etc.) i.e., using sequences that have already been created.

They help to reduce longer loops and make your code easier to read and maintain.

The following example shows how to do it:

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] 
print("Originallist ", my_list)
all_indexes = [a for a in range(len(my_list)) if my_list[a] == 'Guru']
print("Indexes for element Guru : ", all_indexes)

Output:

Originallist  ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
Indexes for element Guru :  [0, 3, 6]

Using Enumerate to get the index of an element in a list

Enumerate() function is a built-in function available with Python. You can make use of enumerate to get all the indexes of the element in a list. It takes input as an iterable object (i.e., an object that can be looped), and the output is an object with a counter to each item.

The following example shows how to make use of enumerate on a list to get all the indexes for a given element.

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] 
print("Originallist ", my_list)
print("Indexes for element Guru : ", [i for i, e in enumerate(my_list) if e == 'Guru'])

Output:

Originallist  ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
Indexes for element Guru :  [0, 3, 6]

Using filter to get the index of an element in a list

The filter() method filters the given list based on the function given. Each element of the list will be passed to the function, and the elements required will be filtered based on the condition given in the function.

Let us use the filter() method to get the indexes for the given element in the list.

The following example shows how to make use of filter on a list.

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] 
print("Originallist ", my_list)
all_indexes = list(filter(lambda i: my_list[i] == 'Guru', range(len(my_list)))) 
print("Indexes for element Guru : ", all_indexes)

Output:

Originallist  ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
Indexes for element Guru :  [0, 3, 6]

Using NumPy to get the index of an element in a list

NumPy library is specially used for arrays. So here we will make use of NumPy to get the index of the element we need from the given list.

To make use of NumPy, we have to install it and import it.

Here are the steps for the same:

Step 1) Install NumPy

pip install numpy

Step 2) Import the NumPy Module.

import numpy as np

Step 3) Make use of np.array to convert list to an array.

my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] 
np_array = np.array(my_list)

Step 4) Get the index of the element you want, using np.where().

item_index = np.where(np_array == 'Guru')[0]

The final working code with output is as follows:

import numpy as np
my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] 
np_array = np.array(my_list)
item_index = np.where(np_array == 'Guru')[0]
print("Originallist ", my_list)
print("Indexes for element Guru :", item_index)

Output:

Originallist['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
Indexes for element Guru : [0 3 6]

Using more_itertools.locate() to get the index of an element in a list

The more_itertools.locate() helps to find the indexes of the element in the list. This module will work with Python version 3.5+. The package more_itertools has to be installed first to make use of it.

The following are the steps to install and make use of more_itertools:

Step 1) Install more_itertools using pip (Python package manager). The command is

pip install more_itertools

Step 2) Once the installation is done, import the locate module as shown below.

from more_itertools import locate

Now you can make use of locate module on a list as shown below in the example:

from more_itertools import locate
my_list = ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru'] 
print("Originallist : ", my_list)
print("Indexes for element Guru :", list(locate(my_list, lambda x: x == 'Guru')))

Output:

Originallist :  ['Guru', 'Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
Indexes for element Guru : [0, 3, 6]

FAQs

The index() method raises a ValueError when the element is missing. Wrap the call in a try-except block, or first test membership with the in operator, so a missing value does not crash your program.

The value returned by index() is always a non-negative position counted from the start. You may pass negative start or end arguments to bound the search, but index() itself never returns a negative index for a found element.

Yes. index() compares elements exactly, so ‘Guru’ and ‘guru’ are treated as different values. Searching for the wrong case raises a ValueError. Normalize strings with lower() before searching if you need case-insensitive matching.

Use the in operator, for example if ‘Guru’ in my_list. It returns True or False without raising an error, so you can safely call index() only when the element is actually present in the list.

For a single lookup, the built-in index() is already efficient because it stops at the first match. To find many values repeatedly, build a dictionary mapping each value to its index, which turns each search into a fast constant-time operation.

Python lists provide index() but have no find() method. index() raises a ValueError when the element is absent, whereas the string find() returns -1. For lists, catch the error or check membership with the in operator instead.

Locating an element’s index helps map categorical labels to numeric positions, find where a predicted class appears, or align feature columns before training. NumPy extends this with np.where() for fast index lookups across large arrays and datasets.

Yes. GitHub Copilot and agentic AI assistants generate index(), enumerate(), and comprehension-based lookups from a plain comment, suggest safe error handling for missing values, and refactor loops, though you should still test edge cases and confirm the returned positions.

Summarize this post with: