list indices must be integers or slices is one of the most common TypeError messages that Python beginners encounter. It appears when you try to access an element in a list using an index that Python does not recognize as a valid whole number or slice object. Because Python lists are ordered collections that rely on positional numbering, passing a string, float, or other unsupported type inside square brackets breaks the language’s fundamental indexing rules. Understanding why this error occurs—and how to fix it—is essential for anyone learning Python programming, working with data structures, or debugging scripts that manipulate sequences Not complicated — just consistent..
What Does “List Indices Must Be Integers or Slices” Mean?
In Python, a list is a mutable sequence that stores items in a specific order. Day to day, each item is assigned a position starting from zero. Day to day, to retrieve or modify an item, you place an index inside square brackets immediately after the list name. Take this: if you have fruits = ["apple", "banana", "cherry"], then fruits[0] returns "apple" Worth keeping that in mind..
The error message list indices must be integers or slices tells you that whatever you placed inside those brackets is not an integer (int) and not a slice (slice). Python expects a whole number such as 0, 1, or -1, or a slice expression like 1:3. When you provide something else—such as "0", 1.5, or None—the interpreter raises a TypeError and stops execution Still holds up..
This error is Python’s way of enforcing type safety at the sequence level. It prevents ambiguous behavior that could arise if the language tried to guess whether "1" meant the string "1" or the integer position 1 That alone is useful..
Common Causes of the Error
Several everyday coding mistakes trigger this TypeError. Recognizing them helps you debug faster and write cleaner code Simple, but easy to overlook..
Using Strings as Indices
One of the most frequent causes is treating a list like a dictionary. Dictionaries allow string keys, but lists do not The details matter here..
scores = [85, 90, 78]
print(scores["math"]) # TypeError: list indices must be integers or slices
Here, "math" is a string. Python cannot use it to locate a position in scores.
Using Float Numbers as Indices
Even if a float represents a whole number, Python rejects it as a list index.
data = [10, 20, 30]
index = 1.0
print(data[index]) # TypeError: list indices must be integers or slices
Although 1.0 is numerically equal to 1, its type is float, not int Not complicated — just consistent..
Using None or Other Objects
Passing None, a boolean in certain contexts, or a custom object also results in the same error.
items = ["a", "b", "c"]
print(items[None]) # TypeError
Confusing List Methods with Indexing
Beginners sometimes attempt to index into the result of a method that returns None, such as .append() or .sort().
nums = [3, 1, 2]
print(nums.sort()[0]) # TypeError: 'NoneType' object is not subscriptable
While this produces a slightly different message, it stems from the same misunderstanding of how list operations work Not complicated — just consistent..
How to Fix the Error: Step-by-Step Solutions
Fixing list indices must be integers or slices usually involves converting the offending value into a proper integer or rethinking whether you should be using a list at all Not complicated — just consistent..
1. Convert String Indices to Integers
If your index arrives as a string—perhaps from user input or a JSON file—wrap it in int().
user_input = "2"
values = [100, 200, 300]
index = int(user_input)
print(values[index]) # Output: 300
Always validate that the string actually contains a number before converting, or wrap the conversion in a try-except block to handle invalid input gracefully The details matter here..
2. Convert Float Indices to Integers
Use int() to truncate a float toward zero, or use round() if you need nearest-integer behavior Simple, but easy to overlook..
position = 2.7
matrix = [5, 10, 15, 20]
print(matrix[int(position)]) # Output: 15
3. Use Dictionary Syntax for Key-Based Lookups
If you need to look up items by name rather than by position, switch from a list to a dictionary.
# Instead of this:
# students = ["Alice", "Bob", "Charlie"]
# print(students["Alice"]) # Error
# Do this:
students = {"Alice": 85, "Bob": 90, "Charlie": 78}
print(students["Alice"]) # Output: 85
4. Use Slice Notation Correctly
Slices require the start:stop[:step] format inside brackets. Each component should be an integer or omitted entirely Most people skip this — try not to..
letters = ["a", "b", "c", "d", "e"]
print(letters[1:4]) # Output: ['b', 'c', 'd']
print(letters[:3]) # Output: ['a', 'b', 'c']
print(letters[::2]) # Output: ['a', 'c', 'e']
5. Loop with enumerate() or range()
When iterating over a list and you need both the index and the value, avoid manual index management that can introduce invalid types.
words = ["red", "green", "blue"]
for index, word in enumerate(words):
print(index, word)
Code Examples: Before and After
Seeing the error in context makes the fix easier to remember It's one of those things that adds up..
Example
Example
Before – the error occurs
# Imagine we receive a position from a web form as a string
raw_position = "3"
colors = ["red", "green", "blue", "yellow"]
# The developer mistakenly treats the string as an index directly
print(colors[raw_position]) # TypeError: 'str' object is not subscriptable
After – proper conversion
raw_position = "3"
colors = ["red", "green", "blue", "yellow"]
position = int(raw_position) # convert the string to an integer
print(colors[position]) # Output: yellow
If the source of the value might be malformed, guard the conversion with exception handling:
try:
position = int(raw_position)
except ValueError:
print("Invalid position supplied")
position = None # or decide on a default index
Example – Float index handling
Before
step = 2.9
matrix = [10, 20, 30, 40, 50]
print(matrix[step]) # TypeError: 'float' object is not subscriptable
After
step = 2.9
matrix = [10, 20, 30, 40, 50]
print(matrix[int(step)]) # Output: 30 (truncates toward zero)
If rounding is preferred:
print(matrix[round(step)]) # Output: 30 as well, because 2.9 rounds to 3
Example – Switching to a dictionary for name look‑ups
Before
names = ["Alice", "Bob", "Charlie"]
print(names["Alice"]) # TypeError: 'str' object is not subscriptable
After
names = {"Alice": "red", "Bob": "green", "Charlie": "blue"}
print(names["Alice"]) # Output: red
Example – Correct slice syntax
Before
items = ["a", "b", "c", "d"]
print(items[1, 3]) # TypeError: list indices must be integers or slices, not 'tuple'
After
items = ["a", "b", "c", "d"]
print(items[1:3]) # Output: ['b', 'c']
Conclusion
The list indices must be integers or slices error is a clear indicator that the value used to address a list is not an integer (or a slice object). By converting string or float inputs to int, employing proper slice notation, or redesigning the data structure when key‑based access is needed, the problem disappears. Now, remember to validate external input, handle conversion failures gracefully, and choose the appropriate collection type for the task at hand. With these practices, the offending TypeError becomes a non‑issue, and your code will reliably manipulate lists in Python Worth knowing..