I keep getting this error:
line 4, in timesTwo
IndexError: list index out of range
for this program:
def timesTwo(myList):
counter = 0
while (counter <= len(myList)):
if myList[counter] > 0:
myList[counter] = myList[counter]*2
counter = counter + 1
elif (myList[counter] < 0):
myList[counter] = myList[counter]*2
counter = counter + 1
else:
myList[counter] = "zero"
return myList
I’m not exactly sure how to fix the error. Any ideas?
You are setting the upper-bound of the
whileloop to the length ofmyList, which means that the final value of counter will be the length. Since lists are indexed starting at 0, this will cause an error. You can fix it by removing the=sign:Alternatively, you could do this in a
forloop that may be a bit easier to handle (not sure if this fits your use case, so the above should work if not):