TypeError: tuple indices must be integers or slices, not str

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

TypeError: tuple indices must be integers or slices, not str #

The Python "TypeError: tuple indices must be integers or slices, not str" occurs when we use a string instead of an integer to access a tuple at a specific index. To solve the error, use the int() class to convert the string to an integer, e.g. my_tuple[int(my_str)].

typeerror tuple indices must be integers or slices not str

Here is an example of how the error occurs.

main.py
my_tuple = ('a', 'b', 'c') my_str = '1' # ⛔️ TypeError: tuple indices must be integers or slices, not str result = my_tuple[my_str]

The error is caused because we are using a string as a tuple index.

We have to use an integer (e.g. my_tuple[2]) or a slice (e.g. my_tuple[0:2]) for tuple indices.
main.py
my_tuple = ('a', 'b', 'c') my_str = '1' # ✅ convert str to int result = my_tuple[int(my_str)] print(result) # 👉️ 'b'

If you meant to declare a dictionary, make sure to use curly braces (not parentheses).

main.py
my_dict = {} my_dict['name'] = 'Alice' my_dict['age'] = 30 print(my_dict) # 👉️ {'name': 'Alice', 'age': 30}

If you are iterating over a tuple of dictionaries, make sure to access key-value pairs of the dictionary on each iteration.

main.py
my_tuple = ( {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}, ) for entry in my_tuple: print(entry['id']) print(entry['name'])

We used a for loop to iterate over a tuple of dictionaries.

The entry variable stores a dictionary on each iteration, so you can access it at a specific key to get the corresponding value.

You can use an index to access a specific dictionary in the tuple and then access a key in the dictionary.

main.py
my_tuple = ( {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}, ) result = my_tuple[0]['name'] print(result) # 👉️ 'Alice'

We access the tuple item at index 0 and then access the name key of the dictionary.

If you have a dictionary with a tuple value, access the specific key before accessing an index.

main.py
my_dict = { 'fruits': ('apple', 'banana', 'kiwi') } result = my_dict['fruits'][0] print(result) # 👉️ 'apple'

If you need to iterate over a dictionary, use the dict.items() method.

main.py
my_dict = {'name': 'Alice', 'age': 30} for key, value in my_dict.items(): print(key, value) # 👉️ name Alice, age 30

The dict.items method returns a new view of the dictionary's items ((key, value) pairs).

If you need to get a slice of a tuple, use a colon to separate the start and end indices.

main.py
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).

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
Tuples are very similar to lists, but implement fewer built-in methods and are immutable (cannot be changed).

If you aren't sure what type of object a variable stores, use the type() class.

main.py
my_tuple = ('a', 'b', 'c') print(type(my_tuple)) # 👉️ <class 'tuple'> print(isinstance(my_tuple, tuple)) # 👉️ True my_list = ['a', 'b', 'c'] 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.

Conclusion #

The Python "TypeError: tuple indices must be integers or slices, not str" occurs when we use a string instead of an integer to access a tuple at a specific index. To solve the error, use the int() class to convert the string to an integer, e.g. my_tuple[int(my_str)].

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.