简体   繁体   中英

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

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)

You're getting a index out of range exception because there is nothing in your list. If you want to loop 5 times and set x[i] = 0 there has to be a x[i] first.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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