List indices must be integers or slices, not str?


#1
operator = ['+', '-', '/', '*', '']

while True:
    z = str(input("Enter an operator. (*, /, +, -)"))
    for n in operator:
        if z == operator[n]:
            print("No valid operator detected.")

Throwing the error

Traceback (most recent call last):
  File "C:/Users/User/Documents/Python Scripts/list test for strings.py", line 6, in <module>
    if z == operator[n]:
TypeError: list indices must be integers or slices, not str

Why? I didn’t think list indices had to be integers. I thought I could put anything into a list, like a string or an integer, or a combination. The course over here says as much


#2

This is because of your for loop.

In this case ‘n’ will return the value and not the index number of its position in the array. Therefore in your if statement what you are litterly saying in the first iteration is if z == operator['+']: which is afcourse incorrect since there is no index ‘+’. This should be a number and not a string.

To fix this you simply have to use n in your if statement instead of operator[n].

operator = ['+', '-', '/', '*', '']

while True:
    z = str(input("Enter an operator. (*, /, +, -)"))
    for n in operator:
        if z == n:
            print("No valid operator detected.")