How to return the index of an element in a list using Python?

In Python, you can use the index() method to return the index of an element in a list. The index() method takes one parameter, which represents the element to be searched for. If the element is found, it will return the index of its first occurrence; if the element is not found, it will raise a ValueError exception.

Here is an example:

fruits = ['apple', 'banana', 'orange', 'apple', 'pear']

index = fruits.index('banana')
print(index)  # 输出: 1

index = fruits.index('apple')
print(index)  # 输出: 0

index = fruits.index('grape')  # 抛出 ValueError 异常

Note that the index() method only returns the index value of the first occurrence. If you want to return all occurrence index values, you can use list comprehension or iterate through a loop.

bannerAds