Borislav Hadzhiev
Fri Apr 22 2022·3 min read
Photo by Kenny Webster
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 backwards 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 idx = 3 if len(my_tuple) > idx: print(my_tuple[idx]) else: # 👇️ this runs print(f'index {idx} is out of range')
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).
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()
function, 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 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, the item.
An alternative approach to handle the "IndexError: tuple index out of range"
exception is to use a try/except
block.
my_tuple = ('a', 'b', 'c') try: result = my_tuple[100] except IndexError: 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.
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()
constructor