Menu Close
list index() method

In this tutorial, we are going to learn about the Python list index() method. In Python, the list index() python is a built-in list method that is used to return the index number of the first occurrence of an element.
In the previous tutorial, we have seen all about the Python list extend() method and list count() method.

List index() Method

The Python list index() method is a built-in method, which is used to return the index number of the element at the first occurrence.

Syntax of list index() method:

list.index(element, start, end)

list index() method parameters:

List index function takes three parameters, element, start, and end:

  • Element:- Element to search for.
  • Start:- ( Optional ) Start searching from this index number.
  • End:- ( Optional ) End the searching on this index number.

Return Value of List index() method.

The List index() python returns the index number of the given element to the list.
If the element is not found, the ValueError exception is raised.

Note:- The list index function returns the index number of the only first occurrence of the element.

List index() method example:

Example 1:-

fruits = ['apple', 'banana', 'cherry', 'Mango', 'Papaya', 'cherry']
x = fruits.index('cherry')
print("The index value of \'cherry\':- ", x)


The index value of 'cherry':-  2

If the element is not present in the list, you will get a ValueError.

Example 2:-

lang = ['Python', 'PHP', 'R', 'Ruby', 'Go']
result = lang.index('JavaScript')


Traceback (most recent call last):
  File "C:\Users\Vishvajit\Desktop\PF Article\Python Basic part1\", line 2, in <module>
    result = lang.index('JavaScript')
ValueError: 'JavaScript' is not in list

index() method with start and end parameters:

lang = ['Python', 'PHP', 'R', 'Ruby', 'Go', 'JavaScript', 'Ruby', 'C', 'C++']

#list index method with element parameter.
result = lang.index('PHP')

#list index method with element and start parameters.
result1 = lang.index('Ruby', 6)

#list index method with element,start and end parameters.
result2 = lang.index('Ruby', 2, 7)




In this tutorial, you have learned the python list index() method to search the index number of a specific element on the first occurrence.
Using the list index method, we can get the index number of elements within a specific range of the index.
I hope you will like the list index() python post, if you like this article, please comment and share it with your friends who want to become Python a programmer from scratch to advance.

For more information:- Click Here

Python List extend() method
Python List insert() Method

Related Posts