Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'type' object is not subscriptable Python

Whenever I try to type-hint a list of strings, such as

tricks: list[str] = []

, I get TypeError: 'type' object is not subscriptable. I follow a course where they use the same code, but it works for them. So I guess the problem is one of these differences between my an the courses environments. I use:

  • vs code
  • anaconda
  • python 3.8.15
  • jupyter notebook

Can someone help me fix that?

I used the same code in normal .py files and it sill doesn't work, so that is probably not it. The python version should also not be the problem as this is kind of basic. Anaconda should also not cause such Error messages. Leaves the difference between vscode and pycharm, which is also strange. Therefore I don't know what to try.

like image 640
Sebastian Avatar asked Aug 30 '25 15:08

Sebastian


2 Answers

You're on an old Python version. list[str] is only valid starting in Python 3.9. Before that, you need to use typing.List:

from typing import List

tricks: List[str] = []

If you're taking a course that uses features introduced in Python 3.9, you should probably get a Python version that's at least 3.9, though.

like image 173
user2357112 supports Monica Avatar answered Oct 14 '25 02:10

user2357112 supports Monica


Python 3.8 is trying to subscript list which is of type type. This will work:

from typing import List
tricks: List[str] = []
like image 45
Sanju sk Avatar answered Oct 14 '25 02:10

Sanju sk