Last modified: Apr 09, 2025 By Alexander Williams

Fix TypeError: List Indices Must Be Integers

Python developers often encounter the error TypeError: list indices must be integers or slices, not str. This error occurs when you try to use a string as an index for a list.

Understanding the Error

Lists in Python are indexed using integers or slices. If you try to access a list with a string, Python raises this error. Here's an example:


fruits = ["apple", "banana", "cherry"]
print(fruits["1"])  # Using string as index


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

Common Causes

The error usually happens in these cases:

1. Using string keys like dictionaries. Lists don't work like dictionaries.

2. Reading data from JSON or other sources and assuming it's a list when it's a dictionary.

3. Forgetting to convert string numbers to integers.

How To Fix the Error

Here are solutions for common scenarios:

1. Convert String Index to Integer

If your index is a string number, convert it to integer first:


fruits = ["apple", "banana", "cherry"]
index = "1"  # String
print(fruits[int(index)])  # Convert to integer


banana

2. Check If You Need a Dictionary

If you're using string keys, you probably need a dictionary instead:


fruit_prices = {"apple": 1.0, "banana": 0.5}
print(fruit_prices["apple"])  # This works


1.0

3. Verify Your Data Structure

When working with JSON data, check if you're dealing with a list or dictionary:


import json

data = '{"fruits": ["apple", "banana"]}'
parsed = json.loads(data)
print(parsed["fruits"][0])  # Access list inside dict


apple

Best Practices

Follow these tips to avoid the error:

1. Always check variable types with type() when unsure.

2. Use try-except blocks to handle potential errors gracefully.

3. When parsing external data, validate the structure first.

For similar Python errors, see our guide on How To Solve ModuleNotFoundError.

Conclusion

The TypeError: list indices must be integers or slices, not str is easy to fix once you understand it. Always use integers for list indices or switch to dictionaries for string keys. Remember to check your data types and structure when working with complex data.