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

3D illustration of a robot trying to open a numbered locker with a text label, representing the 'list indices must be integers' TypeError.

If you’ve ever encountered “TypeError: list indices”, this error almost always means one thing: You think you have a Dictionary, but you actually have a List.

The Difference Recap

  • Lists [] use numbers (integers) to access items based on their position (0, 1, 2…). Be sure to distinguish to avoid this error.
  • Dictionaries {} use keys (strings) to access values ("name", "age"…).

The Problem

You try to use a string “key” on a list. This leads to the TypeError: list indices must be integers.

my_data = ["Alice", 25, "Engineer"]

# Trying to access it like a dictionary
print(my_data["name"])

Error: TypeError: list indices must be integers or slices, not str Python is saying: “This is a list! I expect a number like 0 or 1, but you gave me the string 'name'.”

The Fixes

Option 1: Use the correct integer index (if it must remain a list) If TypeError: list indices persist, ensure to check your indices.

print(my_data[0])  # Output: Alice

Option 2: Change it to a Dictionary (Best if you need named keys) If you want to use keys like “name,” your data structure should be a dictionary.

my_data = {
    "name": "Alice",
    "age": 25,
    "job": "Engineer"
}

print(my_data["name"])  # Output: Alice (Works perfectly!)

JSON Data Tip

This often happens when working with JSON data from an API. If the API returns a list of users [{...}, {...}], you cannot just do data['username']. You must first select which user you want by index: data[0]['username'].Pay special attention to TypeError concerning list indices.

Similar Posts

Leave a Reply