📜  Python|处理 index() 中未找到的元素

📅  最后修改于: 2022-05-13 01:55:35.981000             🧑  作者: Mango

Python|处理 index() 中未找到的元素

有时,在使用Python列表时,我们会遇到一个问题,即我们需要检查一个元素是否存在于列表中,以及它出现在哪个索引处。它的方便解决方案是使用index() 。但是,有时可能会出现问题,所需的元素可能不在列表中。让我们讨论一种可以处理此异常的方法。

方法:使用ValueError + try + except

在这个方法中,知道值可能不存在,我们在 try-except 块中捕获错误。 ValueError 在缺席时引发,可用于捕获此特定异常。

# Python3 code to demonstrate working of
# Handling no element found in index()
# Using try + except + ValueError
  
# initializing list
test_list = [6, 4, 8, 9, 10]
  
# printing list
print("The original list : " + str(test_list))
  
# Handling no element found in index()
# Using try + except + ValueError
try :
    test_list.index(11)
    res = "Element found"
except ValueError :
    res = "Element not in list !"
  
# Printing result
print("The value after catching error : " + str(res))
输出 :
The original list : [6, 4, 8, 9, 10]
The value after catching error : Element not in list!