TypeError: List Indices must be integers or slices, not str

The below pasted code gives me error TypeError: list indices must be integers or slices, not str . The code identical to the solution, i copied the solution in jupyter notebook and that gives correct output but my below code is throwing error.

stem_cats = ['Engineering', 'Computer Science', 'Psychology', 'Biology', 'Physical Sciences', 'Math and Statistics']
major_cat =['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
fig = plt.figure(figsize=(18,3))
for x in range(0,6):
    ax = fig.add_subplot(1,6,x+1)
    ax.plot(women['Year'],women[stem_cats[x]],c='blue',label='Women')
    ax.plot(women['Year'],100-women[stem_cats[x]],c='green',label='Men')
    for x,y in ax.spines.items():
        y.set_visible(False)
    ax.set_xlim(1968,2011)
    ax.set_ylim(0,100)
    ax.set_title(stem_cats[x])
    ax.tick_params(bottom="off", top="off", left="off", right="off")
    if x == 0:
        ax.text(2005,87,"Men")
        ax.text(2002,8,"Women")
    elif x == 5:
        ax.text(2005,62,"Men")
        ax.text(2001,35,"Women")
plt.show()

Around which lines of code does the stack trace say the error is? You can start reading it from top to down, it will show you what code calls what code and the bottom of the trace is where the error is generated. (but starting from the top is easier since that’s code you wrote). I suspect there may be indexing operator [] on a list, like lst[] that contains strings.
You can try enclosing your code with triple back ticks ``` so the indentations are normal and more readable

like this

TypeError Traceback (most recent call last)
in
10 ax.set_xlim(1968,2011)
11 ax.set_ylim(0,100)
—> 12 ax.set_title(stem_cats[x])
13 ax.tick_params(bottom=“off”, top=“off”, left=“off”, right=“off”)
14 if a == 0:

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

"off" are deprecated in later versions of matplotlib.
Use boolean value instead. ax.tick_params(bottom=False, top=True, left=False, right=False)

The error message tells you that the input for list indices must be integers or slices and not string. That is, your input for list indices is a string. This is causing an error.

stem_cats is a list.
To access an element, you have to provide integers or slice notation.
The error message tell us that x is a string object.
x is an invalid type to access an element in a list.

To fix it, you have either change x into an integer object if x is a numeric value but in string format. Example:

y = [0, 1, 2]
x = "1" # String object
y[int(x)] # convert x into integer

Or, you have to provide a valid input instead since x cannot be converted into integer.

yes, its throwing error with X but when i am replacing X with ‘A’, then its working fine… Is it because character ‘X’ has some specific meaning ?

I do not follow you. Can you provide with example code?

The code has been pasted below. I replaced X with character ‘a’, it works now… but when i change it again to X, i get same error…

stem_cats = ['Engineering', 'Computer Science', 'Psychology', 'Biology', 'Physical Sciences', 'Math and Statistics']
major_cat =['Biology', 'Computer Science', 'Engineering', 'Math and Statistics']
fig = plt.figure(figsize=(18,3))
for a in range(0,6):
    ax = fig.add_subplot(1,6,a+1)
    ax.plot(women['Year'],women[stem_cats[a]],c='blue',label='Women',linewidth=3)
    ax.plot(women['Year'],100-women[stem_cats[a]],c='green',label='Men',linewidth=3)
    for x,y in ax.spines.items():
        y.set_visible(False)
    ax.set_xlim(1968,2011)
    ax.set_ylim(0,100)
    ax.set_title(stem_cats[a])
    ax.tick_params(bottom="off", top="off", left="off", right="off")
    if a == 0:
        ax.text(2005,87,"Men")
        ax.text(2002,8,"Women")
    elif a == 5:
        ax.text(2005,62,"Men")
        ax.text(2001,35,"Women")
plt.show()

@amjad21khan,

I have edited your code to be more readable.

In the future you can use the markdown back ticks to format your code in the discourse post to be more readable for others to understand faster in order for a faster reply.

Use triple backticks to format a block of code
```python
while x:
x += 1
if x == 4: break
```

Here you go:

while x:
      x += 1
      if x == 4: break
2 Likes
for x in range(0,6):   

x gets assign a number between 0 and 5 inclusive.
Now, x is an int object.

for x,y in ax.spines.items(): 

x assigns to either "left", "right", "top", or "bottom".
Now, x becomes a string object.

Then we have an invalid type to access element within the list stem_cats since x is a string type.

Change x to a will fix the problem because the type of a is not changed.

for a in range(0,6):   

Ohh… I got it… x is used more than once… so the latest assignment is considered while execution. thanks alvin it was great help.

@amjad21khan, you are welcome.