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

avatar

Borislav Hadzhiev

Wed Apr 20 20223 min read

banner

Photo by Don Ross

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

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

typeerror list indices must be integers or slices not str

Here is an example of how the error occurs.

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

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

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

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

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 list of dictionaries, make sure to access key-value pairs of the dictionary on each iteration.

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

We used a for loop to iterate over a list 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 list and then access a key in the dictionary.

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

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

If you have a dictionary with a list 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 got the error when working with a JSON string, make sure to parse the JSON into a native Python object before accessing specific items.

main.py
import json my_json = json.dumps( [ {'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Carl'}, ] ) print(type(my_json)) # 👉️ <class 'str'> # ✅ convert to native Python object my_list = json.loads(my_json) print(my_list[0]['name']) # 👉️ 'Alice' print(my_list[1]['name']) # 👉️ 'Bob' print(type(my_list)) # 👉️ <class 'list'>

The json.loads method parses a JSON string into a native Python object.

Conversely, the json.dumps method converts a Python object to a JSON formatted string.

You can then use integers for list indexes or strings to access a key in a dictionary.

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

main.py
my_list = ['a', 'b', 'c', 'd', 'e'] print(my_list[0:3]) # 👉️ ['a', 'b', 'c'] print(my_list[3:]) # 👉️ ['d', 'e']

The start index is inclusive, whereas the end index is exclusive (up to, but not including).

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

main.py
my_dict = {'name': 'Alice', 'age': 30} print(type(my_dict)) # 👉️ <class 'dict'> print(isinstance(my_dict, dict)) # 👉️ 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.

Use the search field on my Home Page to filter through my more than 1,000 articles.