TypeError: List Indices Must Be Integers or Slices, Not Str — A Python Fix Guide

Hitting “TypeError: list indices must be integers or slices, not str” in Python? This guide explains every cause and gives you practical fixes with real code examples you can use right now.

List Indices Must Be Integers or Slices, Not Str


You’re writing what feels like perfectly reasonable Python code. You index into a list, run the script, and instead of the value you expected, you get:

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

The list indices must be integers or slices, not str error is one of the most common TypeError messages in Python, and it catches both beginners and experienced developers off guard. The reason it keeps appearing is that it usually signals a confusion between two different data structures: lists and dictionaries. Once you understand the distinction clearly, this error becomes easy to spot and easy to fix.


What the Error Is Actually Saying

Python lists are ordered sequences. Each element sits at a numbered position, starting at 0. To get a value out of a list, you use that position number — an integer:

python
fruits = ["apple", "banana", "cherry"]
print(fruits[0])   # "apple"
print(fruits[2])   # "cherry"

You can also use slices, which are ranges built from integers:

python
print(fruits[0:2])  # ["apple", "banana"]

What you cannot do is use a string as an index:

python
print(fruits["apple"])
# TypeError: list indices must be integers or slices, not str

Lists don’t have named keys. Only dictionaries do. When Python sees you trying to access a list with a string, it tells you exactly what went wrong: you used a str where it needed an int or a slice.


The Most Common Causes

1. Treating a List Like a Dictionary

This is the root of most occurrences of this error. It happens when you create a list but write access code that assumes a dictionary:

python
# This is a list, not a dictionary
person = ["Alice", 30, "Engineer"]
print(person["name"])  # TypeError

person is indexed by position, not by key. If you want named fields, you need a dictionary:

python
person = {"name": "Alice", "age": 30, "role": "Engineer"}
print(person["name"])  # "Alice"

The fix here isn’t really a fix at all — it’s choosing the right data structure for what you’re trying to do. If your data has meaningful labels, use a dictionary. If it’s just an ordered collection of values, use a list with integer indexing.

2. Iterating Over a List and Using the Value as an Index

This one trips up a lot of developers. When you loop over a list with for item in my_list, the variable item takes on the actual value at each position — not the index number. Using that value to index back into the list causes the error:

python
colours = ["red", "green", "blue"]
for colour in colours:
    print(colours[colour])  # TypeError — colour is a string, not an int

What you most likely want is one of two things:

Option A: Just use the value directly:

python
for colour in colours:
    print(colour)  # Works fine

Option B: Use enumerate() if you need both the index and the value:

python
for index, colour in enumerate(colours):
    print(index, colour)  # 0 red, 1 green, 2 blue

enumerate() is the clean, Pythonic way to access both position and value in a loop.

3. JSON Data Parsed into a List, Not a Dictionary

This is a particularly sneaky version of the problem. When you load JSON with Python’s json module, the result depends on what the JSON actually contains. A JSON object {} becomes a Python dictionary. A JSON array [] becomes a Python list.

If your JSON is an array at the top level, trying to access it by key will fail:

python
import json

data = json.loads('[{"name": "Alice", "age": 30}]')
print(data["name"])  # TypeError — data is a list, not a dict

The fix is to index into the list first, then access the dictionary inside it:

python
print(data[0]["name"])  # "Alice"

Or loop through all items:

python
for person in data:
    print(person["name"])

This pattern is extremely common when working with API responses. JSON APIs frequently return a top-level array of objects. The habit of always checking type(data) after parsing JSON saves a lot of debugging time. Understanding how data structures work inside larger data pipelines is a key skill — the same discipline applies whether you’re writing a Python script or managing data at scale, as discussed in Why Is Big Data Analytics Very Important?

4. User Input Returns a String, Not an Integer

Python’s input() function always returns a string. If you ask the user to enter a number and then use it as a list index without converting it first, you’ll hit this error:

python
items = ["pen", "notebook", "eraser"]
choice = input("Enter index (0, 1, or 2): ")
print(items[choice])  # TypeError — choice is a str

The fix is to wrap the input() call with int():

python
choice = int(input("Enter index (0, 1, or 2): "))
print(items[choice])  # Works correctly

In production code, you’d want to validate the input before converting it, to handle cases where the user enters something that isn’t a number:

python
try:
    choice = int(input("Enter index (0, 1, or 2): "))
    print(items[choice])
except (ValueError, IndexError):
    print("Please enter a valid index.")

5. Using One List’s Values to Index Another List

This comes up when developers use the string values from one list as indices for another:

python
labels = ["zero", "one", "two"]
values = [10, 20, 30]

for label in labels:
    print(values[label])  # TypeError — label is a string

The fix is to use integer indices or zip() to pair the two lists together:

python
for label, value in zip(labels, values):
    print(label, value)

Or use enumerate() on one list and index the other:

python
for i, label in enumerate(labels):
    print(label, values[i])

6. Converting len() to a String Before Looping

A less obvious version: wrapping len() in str() turns the count into a string. Then looping over that string gives you single character strings as the loop variable — all of which are invalid list indices:

python
my_list = [1, 2, 3, 4, 5]
length = str(len(my_list))  # "5" — a string

for i in length:
    print(my_list[i])  # TypeError — i is "5", a str

The fix is to remove the str() call and use range():

python
for i in range(len(my_list)):
    print(my_list[i])

Or even more directly, just iterate over the list:

python
for item in my_list:
    print(item)

How to Diagnose the Error Fast

When you see TypeError: list indices must be integers or slices, not str, run through this mental checklist:

  1. What type is the object you’re indexing? Use print(type(my_variable)) right before the failing line.
  2. Is it actually a list when you expected a dict? Check with isinstance(my_variable, dict) vs isinstance(my_variable, list).
  3. Are you in a for loop? The loop variable holds the value, not the index. Use enumerate() or range(len()) if you need the position.
  4. Did this come from JSON? Check if the top level is [...] (list) or {...} (dict). Index into the list first.
  5. Does the index come from input()? Wrap it in int().

The type() function is your first stop. Printing the type of any variable you’re unsure about immediately tells you whether you have a list, dict, string, or something else entirely. It’s a habit worth building for any Python debugging session. If you want to go deeper on the tools that make data inspection and analysis cleaner, Introduction to Data Mining is a good read on how data structure understanding scales from scripts to full analytical systems.


Lists vs. Dictionaries: The Core Distinction

Since most occurrences of this error come from mixing up lists and dictionaries, it’s worth making the distinction explicit:

Feature List Dictionary
Created with [...] {...}
Accessed by Integer index (list[0]) String key (dict["key"])
Ordered Yes (Python 3.7+) Yes (Python 3.7+)
Use when Order matters, data is homogeneous Data has meaningful labels

Choosing the right structure upfront prevents this error before it ever appears. The better your intuition for when to use a list versus a dictionary, the fewer of these TypeErrors you’ll encounter. That kind of structural thinking is also what separates ad-hoc scripting from production-quality Python work. If you’re interested in the broader world of coding tools that help developers make better structural decisions, 50 Best Drag and Drop Programming Tools covers a range of tools built to reduce exactly these kinds of friction points in development.


Key Takeaways

The list indices must be integers or slices, not str error means you used a string to index a list, which Python doesn’t allow.

Here’s the short version of everything to check:

  • Lists use integer indices. Dictionaries use string keys. Pick the right structure for your data.
  • In a for item in my_list loop, item is the value, not the index. Use enumerate() for both.
  • JSON arrays [] become Python lists. Index into the list first, then access dict keys inside each item.
  • input() always returns a string. Wrap it in int() before using it as a list index.
  • Use type() and isinstance() to check what you’re actually working with before indexing.
  • Use zip() or enumerate() instead of using one list’s values to index another.

The error has one cause and a handful of common patterns. Spot the pattern, apply the fix, and move on.