深度阅读

How to get the index of an item in a Python list

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

To get the index of an item in a Python list, you can use the index() method of the list object. Here’s an example:

my_list = ["apple", "banana", "cherry", "apple", "cherry"]
index = my_list.index("banana")
print("Index of 'banana':", index)

In this example, we have a list of fruits called my_list. We use the index() method to find the index of “banana” in the list and store it in the index variable. We then print the index.

Note that if the desired item is not in the list, index() will raise a ValueError. To avoid this, you can either check if the item is in the list using the in operator or use a try-except block to catch the error.

博客作者

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