# How To Solve “IndexError: tuple index out of range” in Python

In this article, we will explain what causes IndexError: tuple index out of range in Python. Some common causes of this error such as incorrect comparison conditions in loops or wrong initialization values. Let’s go into the specific situation and figure out how to fix it.

## What causes the error “IndexError: tuple index out of range” in Python

The error occurs when you want to go to an index that is out of range of the tuple. Look at this program that prints out the values in a tuple.

fruits = ("apple", "banana", "cherry")

# Use for loop to iterate over elements in a tuple.
for i in range(3):
print(fruits[i])

Output:

apple
banana
cherry

And when we change range(3) to range(4), the above error occurs:

fruits = ("apple", "banana", "cherry")

for i in range(4):
print(fruits[i])

Output:

Traceback (most recent call last):
File "./example.py", line 3, in <module>
IndexError: tuple index out of range

The tuple has only 3 indexes: 0,1,2 but for loop wants to access the 3rd index position, so the error happens.

## Solutions for “IndexError: tuple index out of range” error

### Using For loop

We can use len() function to check the length of the tuple first and then use a for loop to iterate over the items so we avoid the error.

Example:

fruits = ("apple", "banana", "cherry")

# Use "len()" and for loop
for i in range(len(fruits)):
print(fruits[i])

Output:

apple
banana
cherry

### Using While Loop

fruits = ("apple", "banana", "cherry")
i = 0

while i < len(fruits):
print(fruits[i])
i += 1

Output:

apple
banana
cherry

len() function will return a tuple length of 3, so the loop will run 4 times because the initial value of i is 0. We will not use “<=” in this case, but should only use “<“, the variable i will not be able to equal the length of the tuple, and the code will not access the 4th element of the tuple. So the error won’t happen.

### Using Try… Except to catch this error

We should only loop within the tuple’s index range. Avoid letting the loop access out of the tuple’s scope and make sure the item exists in the tuple. You can use Try… Except to catch this error, preventing the program from stopping.

fruits = ("apple", "banana", "cherry")
try:
for i in range(4):
print(fruits[i])
except IndexError:
print("Something went wrong")

Output:

apple
banana
cherry
Something went wrong

## Summary

The error “IndexError: tuple index out of range” in Python has been solved. In many cases, It would help if you used the len() function to check the range of the tuple first. Pay attention to the index range of the tuple while writing the program so you can avoid this error. We hope you like it. Good luck to you!