List Index Out of Range Error in Python

Overview

In this article, we shall learn about what the Python error “List Index Out Of Range Error” is and how to resolve it.

Scope

  • Cause of the error.
  • Fixing the error by using the range() method.
  • Fixing the error by using the index() method.
  • Fixing the error by using the “in” operator with range.

What causes “list index out of range”?

“list index out of range” is an error that frequently arises in Python, usually while working with lists. The error occurs when we try to access an index in a list that is not in the range of its size. Following are some prominent examples of this problem occurring:

Code

arr = [3, 2, 1]

print(arr[3])

Output

Traceback (most recent call last):

  File "/home/maverick/Documents/dsa/script.py", line 2, in <module>

    print(arr[3])

IndexError: list index out of range

Code

arr = ["red", "pink", "blue"] 

for item in range(len(arr) + 1):

    print(arr[item])

write your code here: Coding Playground

Output

red

pink

blue

Traceback (most recent call last):

  File "/home/maverick/Documents/dsa/script.py", line 3, in <module>

    print(arr[item])

IndexError: list index out of range

Using range()

The method “range” returns a specific range with respect to the size of the given list. It returns a sequence of numbers between the defined range.

Syntax

range(start, stop, step)

Parameters

start

An obligatory number denotes the start of the sequence. The default value is zero.

stop

A number that denotes the end of the sequence.

step

An obligatory integer is required when increasing the iterator increment by more than 1.

Example

arr = ["yellow", "purple", "white"]

for color in range(len(arr)):

    print(arr[color])

write your code here: Coding Playground

Output

yellow

purple

white

Using index()

index() function finds and returns the index of the first occurrence of the given element in the given array. This index value of the last item of the list we use by adding 1 to it. The resulting value is the exact value of length.

arr = [4, 3, 2, 1, 0]

for ind in range(arr.index(arr[-1])+1):

    print(arr[ind])

write your code here: Coding Playground

Output

4

3

2

1

0

Using in

arr = [1, 22, 333]

for item in arr:

    print(item)

write your code here: Coding Playground

Output

1

22

333