如何避免“ IndexError:列表索引超出范围”错误?

时间:2019-03-04 10:37:40

标签: python

假设有一个名为“ my_list”的列表和一个名为“ list_index”的int变量。基本上,列表“ my_list”可能会随时间变化,因此“ list_index”可能会引发“ IndexError: list index out of range”。但是,我只想在发生此错误时进行记录,因为它并不那么重要。为避免此错误,我目前的基本解决方案是:

# My first way
if my_list[list_index: list_index +1]: 
    print('item exists')
else:
    print('item does not exist')

# My second way
if -len(my_list) <= list_index < len(my_list):
    print('item exists')
else:
    print('item does not exist')

除了try / except语句外,还有其他解决方案可以避免“ IndexError:列表索引超出范围”错误吗?

3 个答案:

答案 0 :(得分:1)

您可以使用try-except。

a = [1,2,3]

try:
 print(a[4])
except IndexError:
 pass

答案 1 :(得分:0)

在这种情况下,我们可以做的是知道可能发生的错误,因此我们将易于发生错误的语句封装在try内,并添加带有错误的except块键入我们定义程序遇到错误时应采取的措施。

它的一般语法是

try:
    # statements that can possibly cause an error
except error_type:
    # what to do if an error occurred

所以在这里您提到的错误是IndexError,它在运行时捕获了索引不足异常。因此,一种简洁而有效的方法如下。

try:
    index_value = my_list[list_index]
except IndexError:
    index_value = -1
    print('Item index does not exist')

答案 2 :(得分:0)

使用range(len(LIST)-1)

for i in range(len(LIST)-1):
        if LIST[i] < LIST[i+1]:
            ... # you got an idea; no index error since range(len(LIST)-1)
相关问题