Python

index() method in list

Click for All Topics

index() method in list - Python

  • This method is used to find the index of a specified element in the list.
  • This will return the index position of the first occurrence of an element in the list.
  • It will throw a ValueError when the passed element does not exist in the list.
  • The time complexity of this method is O(n) where n is the number of elements in the list.
  • In this method, you can also specify from where Python can start searching the element and where it has to be searched.

 

Syntax –

list.index(element, start, end)

 

Parameters –

  • element → element that’s index position you want to find.
  • start(optional) → starting position from where you want to search by default its value is 0.
  • end(optional) → end position where you have to search by default its value is the same as the length of the list.

 

Example 1-

				
					my_list=[1,11,111,1111,11111,11111]
index_of_11=my_list.index(11)
print("Index of 11:",index_of_11)

# Output -
# Index of 11: 1
				
			
  • In the above example, first we create a list with some elements and store it in my_list variable.
  • After creating my_list, we find the index position of 11 by using the .index() method and store it in the variable index_of_11.
  • Finally, print the index position of 11 on the output screen.

Example 2- find the index of an element using the start and end parameter

				
					my_list=['Hello', 'Student', 'this', 'is', 'edSlash']
index_of_is=my_list.index('is',1,4)
print("Index Position of 'is' :",index_of_is)

# Output - 
# Index Position of 'is' : 3
				
			

Example 3- find the index of an element that doesn’t exist in the list

				
					my_list=['a','b','c','d','e','f']
print(my_list.index('g'))

# Output -
# Traceback (most recent call last):
 # File "/home/main.py", line 2, in <module>
    # print(my_list.index('g'))
# ValueError: 'g' is not in list
				
			

Example 4- find the index value of an element without using any in-built(.index()) method

				
					lst=[10,20,30,40,50,60,10,70,20]
for i in range(len(lst)):
	if lst[i]==60:
		print(i)
		break

# Output -
# Index value of 60: 5