Code with the error

colors = ["red", "green"]
for color in colors:
    print(colors[color])

Error message (Python 3.12, last line)

TypeError: list indices must be integers or slices, not str

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: Loops

Frequently 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.