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

Finding the index of an item in a list in Python

 

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 

list.index(element,start,end)

 

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 

 

Example:

list= [1,3,5,7,9,1,3,5,7,9]

Output:

 

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

Example:

list= [1,3,5,7,9,1,3,5,7,9]
index= list.index(3)
print("Index of the elelment is:", index)

Output:

 

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.

Example:

list= [1,3,5,7,9,1,3,5,7,9]
index= list.index(3,4)
print("Index of the element is:", index)

Output:

 

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

Example:

list= [1,3,5,7,9,1,3,5,7,9]
index= list.index(3,7,9)
print("Index of the element is:", index)

Output:

 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.

Example:

list= [1,3,5,7,9,1,3,5,7,9]

indices_list = []
previous_index = -1
element = True

while elelment:
   try:
      previous_index = list.index(3, previous_index + 1)
      indices_list.append(previous_index)
   execpt ValueErrror:
      element = False

if len(indices_list) == 0:
   print("The element isn't in the list")
else:
   print("The element is present at the indices: " + str(indices_list))

Output:

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