Indexerror: list Index Out of Range

In this post, we will see about Indexerror: list Index Out of Range in Python.

While working with list, you can access its elements by its index. You will get this error when you are trying to access an index that does not exist.

Let’s see with the help of example.

Output:

ListIndexOutOfRange

You will generally get this error while working with while or for loop in Python.

Let’s understand few common scenarios.

While loop

When you use while loop, you might get Indexerror: list Index Out of Range.

Let’s understand with help of example:

When you run above program, you will get below output:

Can you guess why did we get IndexError: list index out of range?

As we have already printed all the elements of the list and we are trying to access colorList[4], we are getting indexError.
Hint: We have issue in below line.
while i <= len(colorList): We should be iterating from 0 to 3, rather than 0 to 4. In python, list index starts from 0, so we need to change while i <= len(colorList): to while i < len(colorList):

When you run above program, you will get below output:

4
Index: 0 Element: Orange
Index: 1 Element: Blue
Index: 2 Element: Red
Index: 3 Element: Pink

Similarly, you can get this issue in for loop as well.

Recommended way for iterating with index

If you want to iterate with index over loop, you should use enumerate() function.

Here is the example for the same.

Index: 0 Element: Orange
Index: 1 Element: Blue
Index: 2 Element: Red
Index: 3 Element: Pink

As you can see, we don’t have to deal with len(colorList) here. In this case, you won’t get Indexerror: list Index Out of Range

Accessing element as index

Another reason for this error may be when you are trying to access elements as index.

Let’s see with the help of example.

Output:

As you can see, i actually refers to element and we are trying to access as index.That’s why we are getting this error.
To resolve this issue, you just need to print i rather than listInt[i]

That’s all about Indexerror: list Index Out of Range in Python.

Related Posts

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.