All Python errors
TypeError: list indices must be integers or slices
This message means the value inside the square brackets of a list is not a whole number. In a for loop over a list the variable already is the item, so use it directly; otherwise pass an integer position.
Code with the error
colors = ["red", "green"]
for color in colors:
print(colors[color])
Error message (Python 3.12, last line)
Corrected code
colors = ["red", "green"]
for color in colors:
print(color)
Output
red
green
Common causes
- The item from for x in items is used as an index: items[x].
- The index is text typed in quotes: items["0"].
- Division gives a float: items[len(items) / 2]; use //.
- A list is accessed by key as if it were a dictionary.
Practise in the course
Lesson: LoopsFrequently asked questions
How do I get both the position and the item?
Use enumerate: for i, item in enumerate(items).
How do I fix an index calculated by division?
Use integer division //, which gives a whole number.