TypeError: list indices must be integers or slices, not str
TypeError: list indices must be integers or slices, not str in Python means you used text inside square brackets on a list, like items["name"] or items["2"]. Lists are only indexed by whole numbers.
How do I fix TypeError: list indices must be integers or slices, not str?
TypeError: list indices must be integers or slices, not str means you used text inside square brackets on a list. Either the index is a number stored as text, like input() returns, so wrap it in int(). Or the list holds dictionaries and you wrote users["name"], so pick one first: users[0]["name"].
- 1. Print the indexAdd print(type(i), repr(i)) for the value inside the brackets. '2' with quotes is a string.
- 2. Convert text to intValues from input() or files are text. Use int(input(...)) before using them as a position.
- 3. Pick an item firstFor a list of dictionaries, index a position first, users[0]["name"], or loop: for u in users.
What does TypeError: list indices must be integers or slices, not str mean?
A list stores items by position: items[0], items[1] and so on. It has no names, so items["name"] cannot work. Either the value inside the brackets is a number stored as text (from input() or a file), or the thing you are indexing is a list of dictionaries and you forgot to pick one dictionary first.
Why does TypeError: list indices must be integers or slices, not str happen?
1. A number that is really a string
input() and file reads give text. "2" and 2 are different types.
Breaks
names = ["Ada", "Bob", "Cy"]
i = input("Which? ")
print(names[i])Works
names = ["Ada", "Bob", "Cy"]
i = int(input("Which? "))
print(names[i])2. A list of dictionaries treated as one dictionary
users is a list. Pick a user first, then read its key.
Breaks
users = [{"name": "Ada"}, {"name": "Bob"}]
print(users["name"])Works
users = [{"name": "Ada"}, {"name": "Bob"}]
print(users[0]["name"])
for u in users:
print(u["name"])3. Using the loop item as an index
for x in items gives the items themselves, not their positions.
Breaks
fruits = ["apple", "mango"]
for f in fruits:
print(fruits[f])Works
fruits = ["apple", "mango"]
for f in fruits:
print(f)How to find it in your own code
Checklist: 1) print(type(i), repr(i)) for the value inside the brackets. 2) If it is text like '2', convert with int(). 3) If it is a key like 'name', print the list itself: you need to pick an item first (items[0]) or loop over it. 4) If you need positions in a loop, use for i, x in enumerate(items).
Practise type errors
None of the challenges raises this exact error yet. These practise the same kind of bug.
Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.