Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

python - IndexError: Why am I out of range?

I've been reading other answers for "Index out of range" questions, and from what I understand, you can't try to assign a value to a list index that doesn't exist. My first code was:

spam =[]
for i in range(5):
    spam[i]=i
print (spam)

After reading some of the other answers, I realized that, when I used just the range function, i was starting at 0 and couldn't be assigned to the list. So I created the next little bit of code:

spam =[]
for i in range(5):
    i += 1
    spam[i]=i
print (spam)

And I'm still getting the same error. I know that i now gains the value of 1 after the i += 1 portion of the code, so I believe it should be assigning list item 1 as number 1 in the empty spam list, but it's not working that way. Why is the index not being created?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you write:

>>> x = []

You define x as a list. But it is empty.

When you try to run

>>> x[i] = i #let assume i is a number

That mean that you want to change the value of element number i in your array to the value i. But the point is that there is no element number i in you array. Your array is empty without any element. You can use append() method to give an element to your array:

>>> x.append(i)

Works fine. And then you can change the value of this new element using the previous way. Check this:

>>> x  = []
>>> x
[]
>>> i = 0
>>> x[i] = i

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...