How To Resolve IndexError: List Index Out Of Range In Python

IndexError: list index out of range in Python

The “IndexError: list index out of range” error happens when you access an invalid index in your list. To fix the error, let follow the article to better understand.

What causes the error “IndexError: list index out of range” in Python?

In Python,’ list’ is a data type that allows storing various data types inside it and retrieving their values through the position of the elements. In Python, you can say ‘list’ is the most flexible data type.

The error happens when you access an invalid index in your list.

A common cause of this error is that you mistakenly think the index starts at 1 and ends with n. But the fact is that the index of the list starts from 0 and ends with n-1.

Example: 

students = ['John', 'Perter', 'Jame']
print(students[3])

Output:

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

Error explanation: element ‘John’ is at index 0, element ’28 years old’ at index 1, element ‘developer’ at index 2. So accessing the list at index 3 will throw the ‘list index out of range’ error.

How to solve this error?

Use the range() function 

You can use the range() function to avoid errors when accessing list indexes.

Syntax:

range(start,end)

Parameters:

  • start: starting value. The default is 0.
  • end: end value.

Example :

  • Make a list.
  • Use the range() function to print out the list.
students = ['John', 'Perter', 'Jame']

# Use the range() function to print out the list
for i in range(len(students)):
    print(students[i])

Output:

John
Perter
Jame

Use the index correctly

As I should have figured out, the cause of the list wrong index error starts at position 0 and ends at position n-1. So you need to pay attention to access the index correctly.

Example:

  • Make a list.
  • Use the index to access list elements.
students = ['John', 'Perter', 'Jame']

print(students[0])
print(students[1])
print(students[2])

Output:

John
Perter
Jame

Use for loop

You can also use a for loop to output the element of a list.

Example:

  • Make a list.
  • Use a for loop to output the element of a list.
students = ['John', 'Perter', 'Jame']

for s in students:
	print(s)

Output:

John
Perter
Jame

Summary

If you have any questions about the error “IndexError: list index out of range” in Python, please leave a comment below. I will answer your questions. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *