/  Technology   /  Finding the index of an item in a list

Finding the index of an item in a list

Finding the index of an item in a list

The most common operation while working with lists is finding the index of a particular element.

For this, we have a built-in list method called index().

The basic syntax of this is 

As we can see this method takes in a maximum of three parameters.

  • element is the value that we are searching for in the list.
  • start is the value from which the searching must start. (optional)
  • end is the value till which the searching should be done. (optional)

This list method returns the index of the element in the given list. If the value isn’t found in the list, it raises the ValueError.

Note: If there are multiple occurrences of an element in the list, then the index of the element’s first occurrence is returned.

Let’s consider a list with the following elements 

Let’s get the index of element 3 in this list.

What if we want to know the index of the second occurrence of ‘3’?

Here we can take the help of start parameter. We have given ‘4’ as the start parameter i.e. it starts searching for ‘3’ from the 4th index.

Now we’ll try giving the third parameter end as 9 and start as 4.

 We know that 3 isn’t present in this range. So it raises the ValueError.

Let’s learn how to find the indices of an element when there are multiple occurrences of it.

We have taken an empty list named indices_list which will store all the indices of a particular element. The variable previous index is the last found index of the element during the searching process. We have written a try-except block to handle the exception when the given element isn’t present in the list. 

Leave a comment