IndexError: tuple index out of range in Python [Solved]

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
5 min

banner

# IndexError: tuple index out of range in Python

The Python "IndexError: tuple index out of range" occurs when we try to access an index that doesn't exist in a tuple.

Indexes are zero-based in Python, so the index of the first item in the tuple is 0, and the index of the last is -1 or len(my_tuple) - 1.

indexerror tuple index out of range

Here is an example of how the error occurs.

main.py
my_tuple = ('a', 'b', 'c') # โ›”๏ธ IndexError: tuple index out of range print(my_tuple[3])

accessing tuple at non existent index

The tuple has a length of 3. Since indexes in Python are zero-based, the first item in the tuple has an index of 0, and the last an index of 2.

abc
012
If we try to access any positive index outside the range of 0-2, we would get an IndexError.

# Getting the last item of a tuple

If you need to get the last item in a tuple, use -1.

main.py
my_tuple = ('a', 'b', 'c') print(my_tuple[-1]) # ๐Ÿ‘‰๏ธ c print(my_tuple[-2]) # ๐Ÿ‘‰๏ธ b

getting last item of tuple

When the index starts with a minus, we start counting backward from the end of the tuple.

# Getting the length of a tuple

If you need to get the length of the tuple, use the len() function.

main.py
my_tuple = ('a', 'b', 'c') print(len(my_tuple)) # ๐Ÿ‘‰๏ธ 3

getting length of a tuple

The len() function returns the length (the number of items) of an object.

The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

If you need to check if an index exists before accessing it, use an if statement.

main.py
my_tuple = ('a', 'b', 'c') idx = 3 if len(my_tuple) > idx: print(my_tuple[idx]) else: # ๐Ÿ‘‡๏ธ this runs print(f'index {idx} is out of range')

check if index exists before accessing it

If a tuple has a length of 3, then its last index is 2 (because indexes are zero-based).

This means that you can check if the tuple's length is greater than the index you are trying to access.

# Iterating over a tuple with range()

If you are trying to iterate over a tuple using the range() class, use the length of the tuple.

main.py
my_tuple = ('a', 'b', 'c') for i in range(len(my_tuple)): print(i, my_tuple[i]) # ๐Ÿ‘‰๏ธ 0 a, 1 b, 2 c

check if index exists before accessing it

However, a much better solution is to use the enumerate() function to iterate over a tuple with access to the index.

main.py
my_tuple = ('a', 'b', 'c') for index, item in enumerate(my_tuple): print(index, item) # ๐Ÿ‘‰๏ธ 0 a, 1 b, 2 c

iterating over tuple with enumerate

The enumerate() function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the item.

# Using a try/except statement to handle the error

An alternative approach to handle the exception is to use a try/except block.

main.py
my_tuple = ('a', 'b', 'c') try: result = my_tuple[100] except IndexError: # ๐Ÿ‘‡๏ธ this runs print('index out of range')

using try except statement to handle the error

We tried accessing the tuple item at index 100 which raised an IndexError exception.

You can handle the error or use the pass keyword in the except block.

main.py
my_tuple = ('a', 'b', 'c') try: result = my_tuple[100] except IndexError: pass

The pass statement does nothing and is used when a statement is required syntactically but the program requires no action.

# Trying to access an empty tuple at any index causes the error

Note that if you try to access an empty tuple at a specific index, you'd always get an IndexError.

main.py
my_tuple = () print(my_tuple) # ๐Ÿ‘‰๏ธ () print(len(my_tuple)) # ๐Ÿ‘‰๏ธ 0 # โ›”๏ธ IndexError: tuple index out of range print(my_tuple[0])

You should print the tuple you are trying to access and its length to make sure the variable stores what you expect.

Tuples are very similar to lists, but implement fewer built-in methods and are immutable (cannot be changed).

In case you declared a tuple by mistake, tuples are constructed in multiple ways:

  • Using a pair of parentheses () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor

# The error isn't raised when using tuple slicing

Note that the error isn't raised when using tuple slicing.

The syntax for tuple slicing is my_tuple[start:stop:step].

The start index is inclusive and the stop index is exclusive (up to, but not including).
main.py
my_tuple = ('a', 'b', 'c', 'd') print(my_tuple[0:2]) # ๐Ÿ‘‰๏ธ ('a', 'b') print(my_tuple[2:100]) # ๐Ÿ‘‰๏ธ ('c', 'd')

The slice my_tuple[0:2] starts at index 0 and goes up to, but not including index 2.

The slice my_tuple[2:100] starts at index 2 and goes up to, but not including index 100.

If the start index is omitted, it is considered to be 0 and if the stop index is omitted, the slice goes to the end of the tuple.

main.py
print(my_tuple[2:]) # ๐Ÿ‘‰๏ธ ('c', 'd') print(my_tuple[:2]) # ๐Ÿ‘‰๏ธ ('a', 'b')

The slice my_tuple[2:] starts at index 2 and goes to the end of the tuple.

The slice my_tuple[:2] starts at index 0 and goes up to, but not including index 2.

Python indexes are zero-based, so the first item in a tuple has an index of 0, and the last item has an index of -1 or len(my_tuple) - 1.

# Use a try/except statement if taking the index from user input

If you are taking an index from user input, use a try/except statement to handle the error if the user enters an index that is out of range.

main.py
my_tuple = ('a', 'b', 'c', 'd') index = int(input('Enter an index: ')) try: value = my_tuple[index] print(f'โœ… The value is: {value}') except IndexError: print('โ›”๏ธ The specified index does NOT exist')

access index from user input

The tuple has 4 elements, so the last item has an index of 3 because indices are zero-based.

If the user enters an index that is greater than 3, an IndexError is raised an the except block runs.

Otherwise, we access the tuple at the specified index and print the value.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev