1

I have a list in Python, list1, and the following while loop:

j = 0
while list1[j] >= list1[j - 1] and j < len(list1):
    # do something here and return k
    # k is always incremented
    j += k

I got the following error: IndexError: string index out of range

How to fix this error?

1
  • change j = 0 to j = 1. Commented Jun 24, 2015 at 14:54

2 Answers 2

10

You need to start your while condition with the length check. Python short-circuits the operations in your while loop, so when j is too large, it will just throw an error rather than gracefully ending the loop. So like this:

while j < len(list1) and list1[j] >= list1[j - 1]:

Your first iteration of the loop is comparing list1[0] and list1[-1], which is valid, but may not be what you want to be doing (it compares the first and last elements of list1). Depending on your goals, you may or may not wish to start your loop with j = 1.

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

Comments

1

When using an and, if the first condition is false, the second is not even checked. Simply use:

j = 0
while j < len(list1) and list1[j] >= list1[j - 1]:
    # do something here and return k
    # k is always incremented
    j += k

Comments

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.