Borislav Hadzhiev
Last updated: Apr 20, 2022
Photo from Unsplash
The Python "TypeError: tuple indices must be integers or slices, not tuple" occurs when we use a tuple instead of an integer when accessing a tuple at index. To solve the error, correct the assignment or use a colon if trying to get a slice of a tuple.
Here is an example of how the error occurs.
my_tuple = (('a', 'b'), ('c', 'd')) # ⛔️ TypeError: tuple indices must be integers or slices, not tuple result = my_tuple[0, 1]
We passed a tuple between the square brackets when trying to access the item at a specific index.
my_tuple[2]
) or a slice (e.g. my_tuple[0:2]
) for tuple indices.If trying to get an element in a nested tuple, access the nested tuple using square brackets, and use square brackets again to access the specific element.
my_tuple = (('a', 'b'), ('c', 'd')) print(my_tuple[0][0]) # 👉️ 'a' print(my_tuple[0][1]) # 👉️ 'b'
We access the first tuple (index 0
) with the first set of square brackets and
then access the nested tuple at a specific index.
If you need to get a slice of a tuple, use a colon to separate the start and end indices.
my_tuple = ('a', 'b', 'c', 'd', 'e') print(my_tuple[0:3]) # 👉️ ('a', 'b', 'c') print(my_tuple[3:]) # 👉️ ('d', 'e')
The start index is inclusive, whereas the end index is exclusive (up to, but not including).
If you need to access multiple, unrelated tuple items, access them separately.
my_tuple = ('a', 'b', 'c', 'd', 'e') first = my_tuple[0] print(first) # 👉️ 'a' second = my_tuple[1] print(second) # 👉️ 'b'
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()
constructorIf you use numpy
and are trying to access a nested tuple with two indices,
make sure to convert the tuple to a numpy array first.
import numpy as np my_tuple = (('a', 'b'), ('c', 'd'), ('e', 'f')) arr = np.array(my_tuple) result = arr[:, 0] print(result) # 👉️ ['a', 'c', 'e']
The example shows how to get the first item from each nested tuple in the array.
If you aren't sure what type of object a variable stores, use the type()
class.
my_tuple = 0, 1 print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True my_list = ['a', 'b', 'c', 'd', 'e'] print(type(my_list)) # 👉️ <class 'list'> print(isinstance(my_list, list)) # 👉️ True
The type class returns the type of an object.
The isinstance
function returns True
if the passed in object is an instance or a subclass of
the passed in class.