Finding the index of an item in a list
To find the index of an item in a list in Python, you can use the index() method of the list.
To find the index of an item in a list in Python, you can use the index() method of the list. This method returns the index of the first occurrence of the item in the list.
Here's an example:
Find the index of an item in a list in Python using the index() method of the list
python— editable, runs on the server
This will output 2, because 'mango' is the third item in the list and the indices in the list start at 0.
If the item is not in the list, the index() method will raise a ValueError exception. You can handle this exception by using a try-except block.
Handling ValueError raised by index() method in Python
python— editable, runs on the server
This will output -1, because 'grapes' is not in the list.