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

Dung Do Tien Aug 08 2021 175

I have a small project in Python 3.8 and I want to get some Item from an array:

listArr = ["physics", "chemistry", "mathematics", "english"]
itemResult = "1"
subject = listArr[itemResult]
print(subject)

But I got an error: TypeError: list indices must be integers or slices, not str

Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(listArr[itemResult])
TypeError: list indices must be integers or slices, not str

How can I solve this issue?

Have 1 answer(s) found.
  • D

    Developer Aug 08 2021

    Index of an array must be integer, It's not allow string value, so you can cast as bellow:

    listArr = ["physics", "chemistry", "mathematics", "english"]
    itemResult = int("1")
    print(listArr[itemResult]) # output chemistry

    Hope it is useful for you.

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close