深度阅读

How to get the index of an element in Python List

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

To get the index of an element in a Python list, you can use the index() method that is available for lists. Here’s an example:

my_list = [1, 2, 3, 4, 5]
index = my_list.index(3)
print(index)  # Output: 2

In this example, we first define a list my_list containing integers from 1 to 5. We then use the index() method of the list to find the index of the element 3, which is 2. The index() method returns the index of the first occurrence of the specified element in the list.

If the element is not found in the list, the index() method raises a ValueError exception. To avoid this, you can use a conditional check like so:

my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
  index = my_list.index(3)
  print(index)  # Output: 2
else:
  print("Element not found in list")

In this example, we use an if condition to check if the element 3 is present in the list. If it is present, we get its index using index() method. If it is not present, we print a message saying that the element is not found in the list.

相关标签

博客作者

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