TypeError: ‘int’ object is not subscriptable error occurs in Python when you try to perform indexing or slicing operations on an integer. Since integers are not iterable and don’t support indexing or slicing, attempting to access an index or a slice of an integer will trigger the error.
To fix this error:
- Type checking: Before indexing, ensure the variable is of a type that supports subscripting, like a list or tuple. You can use isinstance(variable, (list, tuple)) to check. Convert the data type using appropriate functions and then slice or index.
- Verify return types: Ensure functions return expected types, especially when conditional logic is used, as different branches might return different types.
- Use debugging tools: Implement error-tracking tools and logging to monitor variable types throughout your program’s execution. This helps in identifying where type mismatches occur.
Reproducing the error
The main reason for this error is when a variable expected to be a list, string, or another subscriptable type is an integer.
data = 192146
print(data[1])
Output
TypeError: 'int' object is not subscriptable
How to fix it?
To fix this error, use the str() function to convert the integer to a string, and then you can access the character of the string using the indexing.
data = 192146
res = str(data)
print(res[1])
print(res[2])
Output
9
2
String objects are subscriptable, so converting the integer to a string solves the error.