The Wayback Machine - https://web.archive.org/web/20250228114905/https://www.geeksforgeeks.org/python-list-index/
Open In App

Python List index() – Find Index of Item

Last Updated : 07 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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:

Python List index() – FAQs

What does the index() method do in Python lists?

The index() method in Python lists returns the first occurrence of the specified value. It raises a ValueError if the value is not found in the list.

Can I specify a range to search within using the index() method?

Yes, you can specify a range to search within using the index() method by providing optional start and end parameters. The method will search for the value only within the specified range.

What happens if the index is out of range in Python?

If you try to access an index that is out of range in Python, it raises an IndexError with the message “list index out of range”. This happens because the index you’re trying to access does not exist within the list’s bounds.


Next Article

Similar Reads

three90RightbarBannerImg