0

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?

1 Answer 1

3

You are setting the upper-bound of the while loop to the length of myList, 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:

while (counter < len(myList)):

Alternatively, you could do this in a for loop that may be a bit easier to handle (not sure if this fits your use case, so the above should work if not):

def timesTwo(myList):

  for index, value in enumerate(myList):
    if value is not 0:
      myList[index] *= 2
    else:
      myList[index] = 'zero'

  return myList
Sign up to request clarification or add additional context in comments.

1 Comment

@user1707398 No prob, happy it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.