The TypeError: list indices must be integers or slices, not str is seen when you’re accessing the list with a string object instead of an integer object.
This is a very simple error. The error statement clearly signifies the error. It says that we are indexing the list using a string object instead of an integer or slices
Also check, How to fix the TypeError: list indices must be integers or slices, not a tuple.
Table of Contents
What causes the TypeError: list indices must be integers or slices, not str?
In Python, lists can be indexed only with integer objects or slices. If you index the list of some other datatype objects like str, an error is seen.
Let’s understand this with an example.
lst=['Welcome','to','pythonhowto.com'] index='0' print(lst[index])
Output:
Traceback (most recent call last): File "C:\Users\paian\PycharmProjects\PythonHowTo\venv\Solutions\Test.py", line 3, in <module> print(lst[index]) TypeError: list indices must be integers or slices, not str
We see an error here as the index holds a string-type variable. Refer to the below code-snippet
print(type(index))
gives us
<class 'str'>
To fix this error,
- Use integer objects for indexing the list.
- Convert the string object to an integer object and then index the list
How to fix TypeError: list indices must be integers or slices, not str?
To fix this error, simply use the integer object instead of the str object as shown below
lst=['Welcome','to','pythonhowto.com'] index=0 print(lst[index])
Output:
Welcome
If you are not providing the index manually, but it is fed from somewhere else,( file, dataframe, etc), then convert the string object to an integer object using int() and then index the list. Refer to the below code snippet for more details.
lst=['Welcome','to','pythonhowto.com'] index='0' print(lst[int(index)])
Output:
Welcome
Conclusion
In this article, we have discussed what causes the TypeError: list indices must be integers or slices, not str. We have also discussed how to fix this issue.
We hope this article has been informative. Thanks for reading.