简体   繁体   English

Python 索引超出范围异常

[英]Python index out of range exception

I've tried this:我试过这个:

x = []
for i in range(5)
    x[i] = 0
print(x)

But it gives index out of range exception Why?但它给出了索引超出范围异常为什么?

Because there is not any value in list that's why In this case you have to use append因为列表中没有任何值,所以在这种情况下,您必须使用 append

like

x = []
for i in range(5)
    x.append(0) #x[i] = 0 
print(x)

remove this line x[i] = 0 and put x.append(0)删除此行x[i] = 0并放置x.append(0)

You're getting a index out of range exception because there is nothing in your list.你得到一个index out of range exception ,因为你的列表中没有任何内容。 If you want to loop 5 times and set x[i] = 0 there has to be a x[i] first.如果你想循环 5 次并设置x[i] = 0必须先有一个x[i]

You created an empty list x = [] (not an array) and in a line x[i] = 0 where you are trying to assign element 0 with index=0 which does not exist at the time of initialization, here in your case it will be the first iteration of for loop with i=0 .您创建了一个空列表x = [] (不是数组),并在x[i] = 0行中尝试分配index=0的元素0 ,这在初始化时不存在,这里是您的情况这将是for循环的第一次迭代i=0

Here is the example:这是示例:

>>> x = []
>>> x[0] = 0
 Traceback (most recent call last):
 File "<pyshell#8>", line 1, in <module>
    x[0] = 0
 IndexError: list assignment index out of range

It will not allow you to assign element with index to an empty list.它不允许您将带有索引的元素分配给空列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM