Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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]
>>> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...