How do I fix 'TypeError: list indices must be integers or slices, not str' in Python?

Updated October 2026 · How we answer

Short answerThis happens when you use a string as an index for a list. Convert the value to an integer, or switch to a dictionary if you meant to look items up by name.

Check what type the index is

Python lists are indexed by position, so the index needs to be an integer or a slice. When a string is used, Python raises this error. The string often comes from user input, a split operation, or a value read from a file. Printing the type of the index just before the failing line usually shows the problem.

If the string is a number in text form, convert it with int before using it. If the string is meant to be a name, the data probably belongs in a dictionary. Using a key like data['name'] is clearer than forcing a list to act like one.

Print type(index) before the failing line. Convert numeric text with int(). Use a dictionary for name-based lookups. Check what split() returns before indexing.

Confirm the structure of the data

Sometimes a variable is a dictionary in one part of the program and a list in another. Look at where the value was assigned and confirm its shape. A quick print of the whole object shows whether you are holding the structure you expected.

Common mistakes

  • Converting the wrong value to an integer without checking where the string came from.
  • Assuming a dictionary behaves like a list when you loop through it.
From our shopsCaseMorph: Type an idea, see a custom phone case in seconds, then print a one-of-one.