Table of contents
1.
Introduction
2.
Definition of Python List index()
3.
List index() Method Syntax
4.
Parameters
4.1.
1. element (required)
4.2.
2. start (optional)
4.3.
3. end (optional)
5.
How to Find Index of an Element in a List?
6.
More Examples on List index() Method
6.1.
Example 1: Find the index of an element
6.2.
Python
6.3.
Example 2: Working with the index() method using start & end parameters
6.4.
Python
6.5.
Example 3: Using the index() method with only the start parameter
6.6.
Python
6.7.
Example 4: Handling the case when the element is not present in the list
6.8.
Python
6.9.
Example 5: How to fix "list index out of range" error using index()
6.10.
Python
7.
Reason for the "list index out of range" error
7.1.
1. Accessing an index beyond the size of the list
7.2.
2. Accessing a negative index that is out of range
7.3.
3. Modifying the list size without updating the indices
8.
Frequently Asked Questions
8.1.
What happens if the element is not found in the list when using the index() method?
8.2.
Can we use the index() method to find the index of an element in a specific range of the list?
8.3.
How can we handle the "list index out of range" error when using the index() method?
9.
Conclusion
Last Updated: Jul 31, 2024
Easy

Python List Index()

Author Gaurav Gandhi
0 upvote

Introduction

Python lists are a powerful data structure that allows you to store & manipulate collections of items. One important aspect of working with lists is the ability to find the index of a specific element within the list. In Python, you can use the index() method to accomplish this task. 

Python List Index()

In this article, we will talk about the Python list index() method in detail, like its syntax, parameters, and different examples.

Definition of Python List index()

The Python list index() method is a built-in function that returns the index of the first occurrence of a specified element within a list. It searches the list from left to right & returns the position of the element if found. The index() method is useful when you need to know the location of a particular item in a list, especially when you want to perform operations based on the element's position.

List index() Method Syntax

The syntax for using the list index() method is :

list.index(element, start, end)


Let's break down the parameters:

1. element: The element to be searched for in the list. This is a required parameter.
 

2. start (optional): The position in the list from where the search should start. If not provided, the search starts from the beginning of the list (index 0).
 

3. end (optional): The position in the list where the search should end (exclusive). If not provided, the search continues until the end of the list.


The index() method returns the index of the first occurrence of the specified element. If the element is not found, it raises a ValueError.

Parameters

The list index() method accepts three parameters, one of which is mandatory & two are optional:

1. element (required)

   - This is the element you want to search for in the list.
 

   - It can be of any data type (e.g., integer, string, float, etc.).
 

   - The index() method will return the index of the first occurrence of this element in the list.

2. start (optional)

   - This parameter specifies the starting position from where the search should begin in the list.
 

   - It is an integer value representing the index.
 

   - If not provided, the search starts from the beginning of the list (index 0).
 

   - If the start index is negative, it is treated as offset from the end of the list.

3. end (optional)

   - This parameter specifies the ending position (exclusive) where the search should stop in the list.
 

   - It is an integer value representing the index.
 

   - If not provided, the search continues until the end of the list.
 

   - If the end index is negative, it is treated as offset from the end of the list.


It's important to note that if the specified element is not found within the given range (start to end), the index() method will raise a ValueError.

How to Find Index of an Element in a List?

To find the index of an element in a Python list, you can simply use the index() method & pass the element you want to search for as an argument. 

Let’s see how to do this in a step step manner : 

1. Create a list: Start by creating a list that contains the elements you want to work with. For example:

   my_list = [10, 20, 30, 40, 50]


2. Call the index() method: Use the index() method on the list & provide the element you want to find the index of. For example:

   index = my_list.index(30)


3. Print the result: The index() method will return the index of the first occurrence of the specified element. You can print or use the returned index as needed. For example:

   print("The index of 30 is:", index)


Output:

   The index of 30 is: 2


In this example, the index() method searches for the element `30` in the list `my_list` & returns its index, which is `2`.

If the element is not found in the list, the index() method will raise a `ValueError`. You can handle this exception using a try-except block if needed.

More Examples on List index() Method

Now let's look at some more examples to understand how the list index() method works in different scenarios.

Example 1: Find the index of an element

  • Python

Python

fruits = ['apple', 'banana', 'orange', 'grape']

index = fruits.index('orange')

print("The index of 'orange' is:", index)
You can also try this code with Online Python Compiler
Run Code


Output

The index of 'orange' is: 2


In this example, we have a list of fruits & we want to find the index of the element 'orange'. The index() method returns 2, which is the index of 'orange' in the list.

Example 2: Working with the index() method using start & end parameters

  • Python

Python

numbers = [10, 20, 30, 40, 50, 30, 60, 70]

index = numbers.index(30, 2, 6)

print("The index of 30 between index 2 & 6 is:", index)
You can also try this code with Online Python Compiler
Run Code


Output

The index of 30 between index 2 & 6 is: 2


Here, we specify the start & end parameters to restrict the search range. The index() method looks for the element `30` starting from index 2 & ending before index 6. It returns the index of the first occurrence of `30` within that range.

Example 3: Using the index() method with only the start parameter

  • Python

Python

numbers = [10, 20, 30, 40, 50, 30, 60, 70]

index = numbers.index(30, 4)

print("The index of 30 starting from index 4 is:", index)
You can also try this code with Online Python Compiler
Run Code


Output

The index of 30 starting from index 4 is: 5


In this example, we provide only the start parameter to the index() method. It searches for the element `30` starting from index 4 until the end of the list & returns the index of the first occurrence.

Example 4: Handling the case when the element is not present in the list

  • Python

Python

numbers = [10, 20, 30, 40, 50]

try:

   index = numbers.index(60)

   print("The index of 60 is:", index)

except ValueError:

   print("60 is not present in the list")
You can also try this code with Online Python Compiler
Run Code


Output

60 is not present in the list


When the specified element is not found in the list, the index() method raises a `ValueError`. In this example, we use a try-except block to handle the exception & print a message indicating that the element is not present in the list.

Example 5: How to fix "list index out of range" error using index()

Sometimes, when trying to access an element from a list using an index, you might encounter the "list index out of range" error. This error occurs when you try to access an index that is beyond the size of the list. 

Let’s see an example of how you can use the index() method to fix this error:

  • Python

Python

my_list = [10, 20, 30, 40, 50]

# Trying to access an index that is out of range

try:

   element = my_list[7]

   print("Element at index 7:", element)

except IndexError:

   print("Error: List index out of range")

# Using index() method to check if the index exists

if 7 < len(my_list):

   element = my_list[7]

   print("Element at index 7:", element)

else:

   print("Index 7 is out of range")
You can also try this code with Online Python Compiler
Run Code


Output

Error: List index out of range
Index 7 is out of range


In this example, we first try to access an element at index 7, which is beyond the size of the list `my_list`. This raises an `IndexError` with the message "list index out of range".

To fix this error, we can use the index() method along with the len() function to check if the index we want to access is within the valid range of the list. We compare the desired index with the length of the list using the condition `if 7 < len(my_list)`. If the index is valid, we access the element using `my_list[7]`. Otherwise, we print a message indicating that the index is out of range.

Reason for the "list index out of range" error

The "list index out of range" error occurs when you try to access an element from a list using an index that is outside the valid range of indices for that list. In Python, list indices start from 0 and go up to `length of the list - 1`.

Here are a few reasons why this error might occur:

1. Accessing an index beyond the size of the list

   - If you try to access an index that is greater than or equal to the length of the list, you will get the "list index out of range" error.

   - For example, if a list has 5 elements, the valid indices are 0 to 4. Trying to access an index like 5 or above will raise the error.

2. Accessing a negative index that is out of range

   - Python allows negative indexing, where -1 refers to the last element, -2 refers to the second-to-last element, and so on.

   - However, if you use a negative index that is beyond the valid range (e.g., -6 for a list with 5 elements), you will encounter the "list index out of range" error.

3. Modifying the list size without updating the indices

   - If you remove elements from a list or resize the list, the valid range of indices changes accordingly.

   - If you try to access an index that was valid before the modification but is no longer within the updated range, you will get the "list index out of range" error.


To avoid this error, make sure to:

- Check the length of the list using the `len()` function before accessing an index.

- Ensure that the index you are trying to access is within the valid range of indices for the list.

- Update the indices appropriately if you modify the size of the list.

Frequently Asked Questions

What happens if the element is not found in the list when using the index() method?

If the element is not found in the list, the index() method raises a ValueError.

Can we use the index() method to find the index of an element in a specific range of the list?

Yes, you can pass optional start and end parameters to the index() method to search within a specific range of the list.

How can we handle the "list index out of range" error when using the index() method?

You can use a try-except block to catch the IndexError exception and handle it gracefully, or you can check the length of the list using the len() function before accessing an index.

Conclusion

In this article, we discussed the Python list index() method, which allows you to find the index of an element within a list. We covered the syntax, parameters, and various examples to demonstrate how to use the index() method effectively. We also explained how to handle the "list index out of range" error using the index() method and proper error handling techniques.

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass