TypeError: list indices must be integers or slices, not str
What it means
You put something other than a whole number inside the square brackets of a list. Lists are numbered 0, 1, 2 and so on, so items[0] works, but items['name'] or items[1.5] does not. The last word of the message tells you what you used instead.
1. Using the loop item as if it were a position
This raises the error
Traceback (most recent call last): File "<exec>", line 3, in <module> TypeError: list indices must be integers or slices, not str
The fix
apple banana cherry 0 apple 1 banana 2 cherry
for fruit in fruits hands you each item, not its position, so fruit is already 'apple'. enumerate() gives you both the position and the item.
2. A position worked out with `/` is a float
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: list indices must be integers or slices, not float
The fix
1
/ always returns a float, even 4 / 2 gives 2.0. Floor division // returns an int, which works as a list index.
3. Treating a list of dictionaries as one dictionary
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> TypeError: list indices must be integers or slices, not str
The fix
Ana Ana 31 Ben 25
The outer list needs a number to choose one dictionary, and only then does a key like 'name' work. Data from JSON often has this shape.
When you see this error, check
- Print the value inside the brackets and its
type(). - Use
//instead of/when you work out a position. - Convert text to a number with
int()before using it as an index. - If you want to look things up by name, use a dictionary instead of a list.
Related errors
All Python errors · How to read a traceback · Step through your code