How to Resolve "TypeError: list indices must be integers or slices, not str" in Python
When working with lists in Python, you might encounter the TypeError: list indices must be integers or slices, not str. This error occurs when you attempt to access an element in a list using a string as the index (e.g., my_list['2']) instead of an integer (e.g., my_list[2]). Python lists are ordered collections, and their elements are accessed by their numerical position, which must always be an integer.
This guide will explain the cause of this error, demonstrate the most common scenario that triggers it (user input), and provide the straightforward solution of converting the string to an integer.
Understanding the Error: Positional Indexing in Lists
The key to understanding this error is the difference between how lists and dictionaries are accessed:
- Lists: Are accessed by their integer position (index). The first element is at index
0, the second at1, and so on. - Dictionaries: Are accessed by a key, which can be a string, integer, or other hashable type.
The TypeError is Python's way of telling you that you are trying to use a dictionary-style string key to access a list, which only understands integer positions.
Reproducing the TypeError
The most common cause of this error is using the input() function to get an index from a user. The input() function always returns a string, even if the user types in numbers.
Example of code causing the error:
my_list = ["Apple", "Banana", "Orange"]
print(my_list)
choice = input("Which fruit do you want to pick? (0, 1, or 2): ")
print(f"You chose: {type(choice)}") # Let's inspect the type of 'choice'
# This will fail because 'choice' is a string (e.g., '2'), not an integer (2).
print(f"You picked {my_list[choice]}")
Example Interaction:
['Apple', 'Banana', 'Orange']
Which fruit do you want to pick? (0, 1, or 2): 2
You chose: <class 'str'>
Traceback (most recent call last):
File "main.py", line 9, in <module>
print(f"You picked {my_list[choice]}")
TypeError: list indices must be integers or slices, not str
The Solution: Convert the String to an Integer with int()
To fix this error, you must convert the string containing the number into an actual integer before using it as a list index. The built-in int() function is the perfect tool for this.
Solution:
my_list = ["Apple", "Banana", "Orange"]
print(my_list)
choice_str = input("Which fruit do you want to pick? (0, 1, or 2): ")
try:
# ✅ Correct: Convert the input string to an integer first.
choice_int = int(choice_str)
# Check if the integer is a valid index to prevent IndexError
if 0 <= choice_int < len(my_list):
print(f"You picked {my_list[choice_int]}")
else:
print("That index is out of range.")
except ValueError:
print("Invalid input. Please enter a number.")
except TypeError as e:
print(f"An unexpected TypeError occurred: {e}")
Example Interaction:
['Apple', 'Banana', 'Orange']
Which fruit do you want to pick? (0, 1, or 2): 2
You picked Orange
It's good practice to wrap the int() conversion in a try...except ValueError block to handle cases where the user might enter non-numeric text.
A Note on List Slicing
This TypeError also applies to list slicing. The start, stop, and step values in a slice must also be integers.
Example of code causing the error:
my_list = ["Apple", "Banana", "Orange", "Grape"]
# Incorrect: Using a string '1' in the slice.
sliced_list = my_list['1':3]
Output:
Traceback (most recent call last):
File "main.py", line 4, in <module>
sliced_list = my_list['1':3]
TypeError: slice indices must be integers or None or have an __index__ method
Solution:
my_list = ["Apple", "Banana", "Orange", "Grape"]
# Correct: Use integers for slicing.
sliced_list = my_list[1:3]
print(sliced_list)
Output:
['Banana', 'Orange']
Distinguishing Lists from Dictionaries
If you find yourself frequently trying to use string indices, you may actually need a dictionary, not a list.
- List (use for ordered collections):
fruits = ["apple", "banana"]
print(fruits[0]) # Access by integer position - Dictionary (use for key-value pairs):
fruit_colors = {"apple": "red", "banana": "yellow"}
print(fruit_colors["apple"]) # Access by string key
Conclusion
The TypeError: list indices must be integers or slices, not str is a fundamental error that signals a misunderstanding of how to access list elements.
| The Problem | The Solution |
|---|---|
You are using a string as a list index (e.g., my_list['0']). | Convert the string to an integer first: my_list[int('0')]. |
| You get a string from user input. | The input() function always returns a string. You must convert it with int() before using it as an index. |
| You need to access data by a string name. | You should probably be using a dictionary, not a list. |
By ensuring you only use integers for list indexing and slicing, you can easily avoid this common TypeError.