Reputation: 1043
I'm trying to assign a value to a position in an existing list but I keep getting that my index is out of range. Probably something stupid but I have been 2 hours trying.
Here is my code (I'm getting the error from the last line:
test="2000 and was not However, implemented 1998 it until;9 8 3 4 1 5 7 2"
saver=[]
text=""
textList=[]
positionList=[]
num=0
for l in test.strip().split(";"):
saver.append(l)
print saver
for i in saver[0].split(" "):
textList.append(i)
print textList
for j in saver[1].split(" "):
positionList.append(j)
print positionList
accomodator=[]*len(textList)
for n in range(1,len(textList)):
n=int(n)
if n not in positionList:
accomodator[n-1]=textList[n-1]
Some variables I still havent used but I already declared them, so just ignore them.
Thanks in advance!
Upvotes: 0
Views: 47
Reputation: 9395
Length of accomodator
is zero. It will give out of index error.
Try this:
accomodator=[]*len(textList)
#print str(len(accomodator)) + " "+str(len(textList))
i = 0;
while i<len(textList):
accomodator.append([])
i +=1
After creating accomodator
, increase its length. Or if you know some efficient to increase its length, you can use it.
Upvotes: 0
Reputation: 103457
Your problem is this line:
accomodator=[]*len(textList)
Because an empty list multiplied by any number is an empty list:
>>> [] * 10
[]
You can initialize each element with some default value:
>>> [None] * 10
[None, None, None, None, None, None, None, None, None, None]
So the fix for your code is:
accomodator=[None]*len(textList)
And of course, 0
or -1
or any other value you like would work just as well.
Upvotes: 2