typeerror: list indices must be integers or slices, not str in python

This error occurs when we try to use a string (or any non-integer type) in place of integer or index when trying to extract an element from a list.

Example:

main.py
my_list = [1, 2, 3, 4, 5]
print(my_list["0"])
46 chars
3 lines

Output:

main.py
TypeError: list indices must be integers or slices, not str
60 chars
2 lines

To resolve this error we need to use integers or slices as indices to extract elements from the list.

Example:

main.py
my_list = [1, 2, 3, 4, 5]
print(my_list[0])
44 chars
3 lines

Output:

main.py
1
2 chars
2 lines

We can also use a variable that holds an integer value for indexing.

Example:

main.py
my_list = [1, 2, 3, 4, 5]
index = 0
print(my_list[index])
58 chars
4 lines

Output:

main.py
1
2 chars
2 lines

related categories

gistlibby LogSnag