Python List index()

The Python list index() is a built-in function that searches for a given element from the start of the list and returns the lowest index where the element appears in the list.

In this tutorial, we will learn about the Python list index() method with the help of examples.

Syntax of List index() 

The syntax of the index() method is:

list.index(element, start, end)

index() Parameters

The index() method can take three parameters.

  • element – the element to be searched in a list
  • start (optional) – the position from where the search begins
  • end (optional) – the position from where the search ends

Return Value from List index()

The index() method returns the index of the first occurrence of the specified element in the list. 

If the element is not found in the list, a ValueError exception is raised.

Example 1: Find the index of the element

# Programming list
programming_list = ['C','C#','Python','Java','JavaScript','SQL']

# find the index of Python
index = programming_list.index('Python')
print('The index of Python is :', index)

# find the index of SQL
index = programming_list.index('SQL')
print('The index of SQL is :', index)

Output

The index of Python is : 2
The index of SQL is : 5

Example 2: Index of the Element not Present in the List (ValueError)

# Programming list
programming_list = ['C','C#','Python','Java','JavaScript','SQL','Java','F#','Go']

# find the lowest index of HTML
index = programming_list.index('HTML')
print('The index of HTML is :', index)

Output

Traceback (most recent call last):
  File "c:\Personal\IJS\Code\tempCodeRunnerFile.py", line 6, in <module>
    index = programming_list.index('HTML')
ValueError: 'HTML' is not in list

Example 3: Working of index() method with start and end arguments

If the element is not found within the start and end index Python will raise ValueError: 'item' not in list.

# Programming list
programming_list = ['C','C#','Python','Java','JavaScript','SQL','Java','F#','Go']

# find the lowest index of Java
index = programming_list.index('Java')
print('The index of Java is :', index)

# find the index of Java with Start parameter
index = programming_list.index('Java',4)
print('The index of Java is :', index)

# find the index of Java with Start and End parameter
index = programming_list.index('Java',4,5)
print('The index of Java is :', index)

Output

The index of Java is : 3
The index of Java is : 6
Traceback (most recent call last):
  File "c:\Personal\IJS\Code\main.py", line 14, in <module>
    index = programming_list.index('Java',4,5)
ValueError: 'Java' is not in list
Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like