Skip to content Skip to sidebar Skip to footer

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 wa

Solution 1:

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

Solution 2:

spam=[] creates an empty list of length 0. Both of your suggested loops are then trying to access an element of the list that does not exist. You probably need to do something like:

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

Post a Comment for "Indexerror: Why Am I Out Of Range?"