Open In App

Python List index() – Find Index of Item

Last Updated : 07 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we are going to explore how to find the index of an element in a list and explore different scenarios while using the list index() method. Let’s take an example to find the index of an Item using the list index method.

list index() method searches for a given element from the start of the list and returns the position of the first occurrence.

Python
a = ["cat", "dog", "tiger"]

print(a.index("dog"))

Output
1

Syntax of List index() Method

Syntax: list_name.index(element, start, end) 

Parameters: 

  • element: The element whose lowest index will be returned.
  • start(optional): The position from where the search begins.
  • end(optional): The position from where the search ends.

We will cover different examples to find the index of element in list using Python and explore different scenarios while using list index() method, such as:

Working on the index() With Start and End Parameters

In this example, we find an element in list python, the index of an element of 4 in between the index at the 4th position and ending with the 8th position.

Python
a = [10, 20, 30, 40, 50, 40, 60, 40, 70]

# Find the index of 40 between index positions 4 and 8
res = a.index(40, 4, 8)
print(res)

Output
5

Working of the Index with the Element not Present in the List

In this example, we will see when using index(), it’s important to remember that if the element is not found in the list, Python will raise a ValueError. we can handle this error using a try-except.

Python
a = ['red', 'green', 'blue']

try:
    index = a.index('yellow')
    print(a)
except ValueError:
    print("'yellow' is not in the list")

Output
'yellow' is not in the list

Also Read:


Next Article

Similar Reads