Python:奇怪的列表索引超出范围错误

时间:2018-10-14 10:49:14

标签: python python-3.x

所以我想从num_list弹出所有的'10',但是我在第5行得到这个IndexError,说,IndexError:列表索引超出范围。

is_10=[]
num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
print(len(num_list)) #answer is 26

for i in range(26):
    if num_list[i] == 10:
        is_10.append(num_list.pop(i))
print(is_10)

"Traceback (most recent call last):
File "<stdin>", line 5, in <module>
IndexError: list index out of range"

如果我改为range(25),它会正常运行

is_10=[]
num_list = [422, 136, 524, 85, 96, 719, 85, 92, 10, 17, 312, 542, 87, 23, 86, 191, 116, 35, 173, 45, 149, 59, 84, 69, 113, 166]
print(len(num_list)) #answer is 26

for i in range(25):
    if num_list[i] == 10:
        is_10.append(num_list.pop(i))
print(is_10)
"no error"

0 个答案:

没有答案