python - IndexError : list index out of range - throwing error in Python?

标签 python list error-handling append indexoutofboundsexception

a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
l= []
for i in a:
    if a[i] % 2 == 0 :
        l.append(a[i])

上面的代码不断抛出错误-"IndexError: list index out of range"
我不知道该怎么办?

最佳答案

当执行for i in a时,您将遍历a元素,而不是索引!

您正在尝试访问:a[1],然后是a[4],然后是a[9],然后是a[16] ->,这是导致IndexError的原因。

如果只想遍历索引,请尝试:

>>> for i in range(len(a)):
        if a[i] % 2 == 0 :
            l.append(a[i])


>>> print (l)
[4, 16, 36, 64, 100]

如果您需要值和索引,请使用for index, value in enumerate(a):

关于python - IndexError : list index out of range - throwing error in Python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35983588/

相关文章:

html - 居中下拉列表

c++ - 在C++中,异常/错误是否也设置错误号?

python - 给定一个方法,如何在 Python 3.3 及更高版本中返回它所属的类?

python - 使用子进程发送键盘事件

python - 在 django 的模板循环中使用列表索引查找

Java 泛型放在 Map<String, ?扩展列表<String>>

java - 拥有权限时出现权限被拒绝的错误

mysql - 错误日志-数据库架构?

python - Python 中比较运算符的结合性

python - 将二维列表写入文件、读出并重新使用保存的列表