深度阅读

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

作者
作者
2023年08月22日
更新时间
13.69 分钟
阅读时间
0
阅读量

To find the index of an element in a list in Python, you can use the index() method. The index() method returns the index position of the first occurrence of the specified element in the list. If the element is not present in the list, a ValueError exception is raised.

Here’s an example:

my_list = ['apple', 'banana', 'orange']
index = my_list.index('banana')
print(f"The index of 'banana' is {index}")

Output:

The index of 'banana' is 1

In this example, we define a list of fruits and then use the index() method to find the index position of the element ‘banana’. Since ‘banana’ is present in the list at index 1, the program prints “The index of ‘banana’ is 1”.

If the element is not present in the list, the index() method will raise a ValueError exception:

my_list = ['apple', 'banana', 'orange']
try:
    index = my_list.index('pear')
    print(f"The index of 'pear' is {index}")
except ValueError:
    print("The element 'pear' is not present in the list")

Output:

The element 'pear' is not present in the list

In this example, we try to find the index position of the element ‘pear’, which is not present in the list. Since the index() method raises a ValueError exception in this case, the try block catches the exception and the program prints “The element ‘pear’ is not present in the list”.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。