Last updated: Apr 8, 2024
Reading timeยท5 min
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
.
Here is an example of how the error occurs.
my_tuple = ('a', 'b', 'c') # โ๏ธ IndexError: tuple index out of range print(my_tuple[3])
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
.
a | b | c |
---|---|---|
0 | 1 | 2 |
0-2
, we would get an IndexError
.If you need to get the last item in a tuple, use -1
.
my_tuple = ('a', 'b', 'c') print(my_tuple[-1]) # ๐๏ธ c print(my_tuple[-2]) # ๐๏ธ b
When the index starts with a minus, we start counting backward from the end of the tuple.
If you need to get the length of the tuple, use the len()
function.
my_tuple = ('a', 'b', 'c') print(len(my_tuple)) # ๐๏ธ 3
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.
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')
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.
If you are trying to iterate over a tuple using the range()
class, use the
length of the tuple.
my_tuple = ('a', 'b', 'c') for i in range(len(my_tuple)): print(i, my_tuple[i]) # ๐๏ธ 0 a, 1 b, 2 c
However, a much better solution is to use the enumerate()
function to iterate
over a tuple with access to the index.
my_tuple = ('a', 'b', 'c') for index, item in enumerate(my_tuple): print(index, item) # ๐๏ธ 0 a, 1 b, 2 c
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.
try/except
statement to handle the errorAn alternative approach to handle the exception is to use a try/except block.
my_tuple = ('a', 'b', 'c') try: result = my_tuple[100] except IndexError: # ๐๏ธ this runs print('index out of range')
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.
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.
Note that if you try to access an empty tuple at a specific index, you'd always
get an IndexError
.
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.
In case you declared a tuple by mistake, tuples are constructed in multiple ways:
()
creates an empty tuplea,
or (a,)
a, b
or (a, b)
tuple()
constructorNote that the error isn't raised when using tuple slicing.
The syntax for tuple slicing is my_tuple[start:stop:step]
.
start
index is inclusive and the stop
index is exclusive (up to, but not including).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.
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
.
try/except
statement if taking the index from user inputIf 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.
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')
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.
You can learn more about the related topics by checking out the following tutorials: