This will happen if you try to use an index that is out of range for a string.

The IndexError: list index out of range error occurs in Python when an item from a list is attempted to be accessed that is outside the index range of the list.

Install the Python SDK to identify and fix exceptions

What Causes IndexError

This error occurs when an attempt is made to access an item in a list at an index which is out of bounds. The range of a list in Python is [0, n-1], where n is the number of elements in the list. When an attempt is made to access an item at an index outside this range, an IndexError: list index out of range error is thrown.

Python IndexError Example

Here’s an example of a Python IndexError: list index out of range thrown when trying to access an out of range list item:

test_list = [1, 2, 3, 4]
print(test_list[4])

In the above example, since the list test_list contains 4 elements, its last index is 3. Trying to access an element an index 4 throws an IndexError: list index out of range:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    print(test_list[4])
IndexError: list index out of range

How to Fix IndexError in Python

The Python IndexError: list index out of range can be fixed by making sure any elements accessed in a list are within the index range of the list. This can be done by using the range() function along with the len() function.

The range() function returns a sequence of numbers starting from 0 ending at the integer passed as a parameter. The len() function returns the length of the parameter passed. Using these two methods together for a list can help iterate over it until the item at its last index and helps avoid the error.

The above approach can be used in the earlier example to fix the error:

test_list = [1, 2, 3, 4]

for i in range(len(test_list)):
    print(test_list[i])

The above code runs successfully and produces the correct output as expected:

1
2
3
4

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Sign Up Today!

In line 6(alternative 8). I am getting an error if I use value of range(lens), but if I reduce the value of range(lens-1). I am getting an error and not the correct answer.

For example, for the input "III", I should be getting the value 3, but instead I get the value 2. And for the input "MCMXCIV", I am getting the value 2294 instead of 1994.

In both instances, the last numeral is being skipped out. How to get without causing string index out of range?

And Can someone point out what's going on wrong here?

def romanToInt( s: str) -> int:
    lens = len(s)
    ans = 0
    i = 0

    while (i != lens):

    #for i in range(lens):
        
        print(i)
        print(s[i])
        if(s[i] == 'I' ):
            if(s[i+1] == 'V'): 
                ans = ans + 4
                i += 1
            elif(s[i+1] == 'X' ):
                ans = ans + 9
                i += 1
            else:
                ans +=1
                
        elif(s[i] == 'V' ):
            ans += 5

        elif(s[i] == 'X' ):
            if(s[i+1] == 'L'):
                ans += 40
                i += 1
            elif(s[i+1] == 'C'):
                ans += 90
                i +=1
            else:
                ans += 10
        
        elif(s[i] == 'L' ):
            ans += 50

        elif(s[i] == 'C' ):
            if(s[i+1] == 'D'):
                ans += 400
                i += 1
            elif(s[i+1] == 'C'):
                ans += 900
                i +=1
            else:
                ans += 100
        
        elif(s[i] == 'D' ):
            ans += 500
        
        elif(s[i] == 'M' ):
            ans += 1000
        
        i += 1

    return ans

if __name__ == "__main__":
    a = romanToInt("III")
    print(a)

    b = romanToInt("MCMXCIV")
    print(b)

asked Sep 10, 2019 in Python by (47.6k points)

I'm currently learning python from a book called 'Python for the absolute beginner (third edition)'. There is an exercise in the book which outlines code for a hangman game. I followed along with this code however I keep getting back an error in the middle of the program.

Here is the code that is causing the problem:

if guess in word:

print("\nYes!", guess, "is in the word!") 

# Create a new variable (so_far) to contain the guess 

new = "" 

i = 0 

for i in range(len(word)): 

if guess == word[i]: 

new += guess 

else: 

          new += so_far[i] 

so_far = new

This is also the error it returns:

new += so_far[i] 

IndexError: string index out of range

Could someone help me out with what is going wrong and what I can do to fix it?

edit: I initialised the so_far variable like so:

so_far = "-" * len(word)

2 Answers

answered Sep 10, 2019 by Vishal (106k points)

To get rid of this error you can try the following ways:-

if guess in word: 

print("\nYes!", guess, "is in the word!") 

new = "" 

i = 0 

for i in range(len(word)): 

if guess == word[i]: 

new += guess 

else: 

new += so_far[i] 

so_far = new 

Learn python with the help of this python training and also visit the python interview questions.

What exception will occur if you try to use an index that is out of range for a particular string?

You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist.

What happens if you attempt to access a string using an index?

A string is a sequence of zero or more characters. What happens if you attempt to access a string using an index equal to the string's length? An error will occur, indicating the index is out of range.

Which method would you use to determine whether a substring is the suffix of a string?

The EndsWith method compares the value parameter to the substring at the end of this string and returns a value that indicates whether they are equal.

When you call a string's split method the method divides the string into two substrings?

When you call a string's split method, the method divides the string into two substrings. This is the first index in a string. This will happen if you try to use an index that is out of range for a string. This function returns the length of a string.