Python List index() with Example

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 of the important one 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 will try to limit searching for 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 for index in the list for 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 the all the indexes of element ‘Guru’.

Below given is an example shows how to get all the indexes using 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.

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.

Following example shows how to make use of enumerate on a list to get the all the indexes for 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.

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 will make use of NumPy to get the index of the element we need from the list given.

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

Here are the steps for 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, usingnp.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.

Following are the steps to install and make use of more_itertools

Step1) 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]

Summary

  • The list index() method helps you to find the index of the given element. This is the easiest and straightforward way to get the index.
  • 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 list.
  • Besides the built-in list method, you can also make use of other ways to get the index like looping through the list, using list comprehensions, using enumerate(), using a filter, etc.
  • Using for-loop and while-loop to get the multiple indexes of a given element.
  • 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.
  • They help to reduce longer loops and make your code easier to read and maintain.
  • You can make use of enumerate to get all the indexes of the element in a list.
  • Enumerate() function is a built-in function available with python. 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 filter() method filters the given list based on the function given.
  • Numpy library is specially used for arrays. You can make use of NumPy to get the index of the element given in the list.
  • The more_itertools.locate() is yet another python library that helps to find the indexes of the list given.