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. This method returns the index of the first occurrence of the item in the list.
Here's an example:
# Define a list of fruits
fruits = ['apple', 'banana', 'mango', 'orange']
# Find the index of 'mango' in the list
index = fruits.index('mango')
# Print the index
print(index)
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.
# Define a list of fruits
fruits = ['apple', 'banana', 'mango', 'orange']
# Try to find the index of 'grapes' in the list
try:
index = fruits.index('grapes')
except ValueError:
index = -1
# Print the index
print(index)
This will output -1
, because 'grapes'
is not in the list.