When working with various data structures in Python, it is sometimes necessary to find the index of a specific element in a list. This is especially important when dealing with lists where the order of elements matters.
Example
Let’s say we have a list with the following elements:
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
And the goal is to find the position of the element “cherry”.
Solution
To solve this problem, Python has a built-in method called index()
for lists. This method takes one argument – the element whose index is to be found – and returns the first index of that element in the list.
The code to solve this task would be:
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
index = fruits.index("cherry")
print(index)
When you run this code, the output will be 2
, which corresponds to the index of the element “cherry” in the list fruits
.
Limitations of the index()
Method
However, it is important to note that the index()
method will raise a ValueError
exception if the element whose index is being sought is not present in the list. To avoid this, you can first check for the presence of the element in the list using the in
operator. If the element is present, you can safely call the index()
method.
fruits = ["apple", "banana", "cherry", "date", "elderberry"]
if "cherry" in fruits:
index = fruits.index("cherry")
print(index)
else:
print("Element not found in list.")
In this case, if the element “cherry” is not in the list fruits
, the program will print the message “Element not found in list.”