IndexError : List Index Out of Range

Last Updated On Thursday 2nd Jun 2022

IndexError List Index Out of Range

IndexError: List Index out of range.Avoiding Index Errors When Working with Lists

  • One type of error is common to see when you’re working with lists for the first time.
  • Let’s say you have a list with three items, and you ask for the fourth item.
	students = ['benny', 'alice', 'tony', 'sam']
print(students[4])
	
	Traceback (most recent call last):
 File "students.py", line 2, in <module>
 print(students[4])
IndexError: list index out of range
	

Python attempts to give you the item at index 4. But when it searches the list, no item in students has an index of 4.

But in Python the fourth item is number 3, because it starts indexing at .

IndexError List Index Out of Range

An index error means Python can’t find an item at the index you requested. If an index error occurs in your program, try adjusting the index you’re asking for by one. Then run the program again to see if the results are correct.

  • Keep in mind that whenever you want to access the last item in a list you use the index -1. This will always work, even if your list has changed size since the last time you accessed it.
	students = ['benny', 'alice', 'tony', 'sam']
print(students[-1])
	

The index -1 always returns the last item in a list, in this case the value ‘sam’.

	sam
	

The only time this approach will cause an error is when you request the last item from an empty list.

	students = []
print(students[-1])
	

No items are in motorcycles, so Python returns another index error.

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

If an index error occurs and you can’t figure out how to resolve it, try printing your list or just printing the length of your list.Because It can help you sort out such logical errors.

References