IndexError: list index out of range

IndexError: list index out of range How To Fix

My code is correct still facing IndexError: list index out of range, This is a common error that occurs when working with lists in Python. This error message is indicating that you are trying to access an index in a list that does not exist please note list starts with 0, not 1. In other words, you are trying to access an element at an index that is greater than the size of the list may be 1 become 0, 2 become 1 and more.

For more clarification see the below example.

Wrong Code

list = [ "a", "b", "c"]

print(list[3])

Error Massage

Traceback (most recent call last):
  File "/home/kali/python/webproject/error/main.py", line 3, in <module>
    print(list[3])
IndexError: list index out of range

Wrong code line

print(list[3])

Correct code line

print(list[2])

OR

print(list[3 - 1])

WHY

# list starts with 0
list = [ "a", "b", "c"]
#      [ "0", "1", "2"] 
print(list[2]) # a=0, b=1, c=2
  • Wrong action: print(list[3]) 
  • Correct action: print(list[2])
  • Convert 3 into a 2.

Entire Correct Code line

list = [ "a", "b", "c"] #c=2

print(list[2])

What is IndexError: list index out of range?

In Python, We face this error when working with lists in Python. This error message is indicating that you are trying to access an index in a list that does not exist please note list starts with 0, not 1.

How to fix IndexError: list index out of range?

if you want to fix this error without changing your code then use (list[number_of_lst name – 1]).
This is also one of the best methods to fix this error.

For more information Visit YouTube Channel.

Scroll to Top
Mother’s Day Python Code Love calculator Miss Universe And You Check Your Love Score With K-POP Idols Check Your Love Score With Childhood Crush