In Python, the index() method is used to find the first occurrence of a specified value in a list. It returns the index of the value if found, otherwise it raises a ValueError if the value is not present.
Syntax:
python
list.index(element, start, end)
– element: The value to search for.
– start (optional): The position to start the search.
– end (optional): The position to end the search.
Example:
python
numbers = [10, 20, 30, 40, 50]
index = numbers.index(30)
print(index) # Output: 2
Handling ValueError:
To avoid ValueError, you can use a conditional check:
python
if 60 in numbers:
print(numbers.index(60))
else:
print(“Value not found”)
The index() method is useful for locating the position of an element in a list, especially when dealing with lists containing unique values or needing to know the first occurrence.