Python List index() Method

The index() method in Python is a built-in function used to find the index of the first occurrence of a specified item in a list. This method is used to search for an element in a list and returns the index of the first occurrence of the item. If the item is not found, the method raises a ValueError.

Syntax

list.index(item, start, end)

Parameters

  • item: The item to be searched in the list.
  • start (optional): The starting index to search for the item. The default value is 0, which means the search starts from the beginning of the list.
  • end (optional): The ending index to search for the item. The default value is the end of the list. If the value is negative, the search is performed from the end of the list.

Examples

Example 1: Finding the Index of an Element in a List

Let’s consider a list and try to find the index of an element in the list using the index() method:

a = ["dog", "cat", "horse", "bird"]
x = a.index("horse")
print(x)

In this example, we have created a list a containing four elements. We have used the index() method to find the index of the element “horse”. The method returns the index of the first occurrence of the item in the list, which is 2 in this case. Finally, we have printed the index.

Example 2: Finding the Index of an Element within a Range

You can also search for an element within a range in the list:

a = ["dog", "cat", "horse", "bird", "dog"]
x = a.index("dog", 1, 4)
print(x)

In this example, we have created a list a containing five elements. We have used the index() method to find the index of the element “dog” within the range 1 to 4. The method returns the index of the first occurrence of the item within the specified range, which is 3 in this case. Finally, we have printed the index.

Example 3: Finding the Index of an Element That Does Not Exist

If the item is not found in the list, the index() method raises a ValueError:

a = ["dog", "cat", "horse", "bird"]
try:
    x = a.index("monkey")
    print(x)
except ValueError as e:
    print("Item not found in the list")

In this example, we have created a list a containing four elements. We have used the index() method to find the index of the element “monkey”. Since the element does not exist in the list, the method raises a ValueError and we have handled it using a try-except block. In the exception block, we have printed a message “Item not found in the list”.

In conclusion, the index() method in Python is a useful function for finding the index of a specified item in a list. You can search for an element in the list or within a range and the method returns the index of the first occurrence of the item. If the item is not found, the method raises a ValueError.

Leave a Reply

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