Editor

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

Broken
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruits[fruit])
Output
Traceback (most recent call last):
  File "<exec>", line 3, in <module>
TypeError: list indices must be integers or slices, not str

The fix

Fixed
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit) # the loop already gives you the item
for i, fruit in enumerate(fruits):
print(i, fruit) # enumerate() when you need the position too
Output
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.

Try fixing it yourself in the editor

2. A position worked out with `/` is a float

This raises the error

Broken
nums = [3, 8, 1, 9, 4]
middle = nums[len(nums) / 2]
print(middle)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
TypeError: list indices must be integers or slices, not float

The fix

Fixed
nums = [3, 8, 1, 9, 4]
middle = nums[len(nums) // 2] # // keeps it a whole number
print(middle)
Output
1

/ always returns a float, even 4 / 2 gives 2.0. Floor division // returns an int, which works as a list index.

Try fixing it yourself in the editor

3. Treating a list of dictionaries as one dictionary

This raises the error

Broken
users = [{'name': 'Ana', 'age': 31}, {'name': 'Ben', 'age': 25}]
print(users['name'])
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
TypeError: list indices must be integers or slices, not str

The fix

Fixed
users = [{'name': 'Ana', 'age': 31}, {'name': 'Ben', 'age': 25}]
print(users[0]['name']) # first pick a dictionary, then a key
for user in users:
print(user['name'], user['age'])
Output
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.

Try fixing it yourself in the editor

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.

All Python errors · How to read a traceback · Step through your code