NameError: name 'List' is not defined
Question:
I’m really unsure why this isn’t working. Here is the important part of the code (it’s from a leetcode challenge).
The first line throws the NameError.
def totalFruit(self, tree: List[int]) -> int:
pass
If I try importing List
first I get an error No module named 'List'
. I’m using Python 3.7.3 from Anaconda.
Answers:
To be able to annotate what types your list should accept, you need to use typing.List
from typing import List
So did you import List
?
Update
If you’re using Python > 3.9, see @Adam.Er8’s answer
To be able to specify a list of str’s in a type hint, you can use the typing
package, and from typing import List
(capitalized, not to be confused with the built-in list
)
Since Python 3.9, you can use built-in collection types (such as list
) as generic types, instead of importing the corresponding capitalized types from typing
.
This is thanks to PEP 585
So in Python 3.9 or newer, you could actually write:
def totalFruit(self, tree: list[int]) -> int: # Note list instead of List
pass
without having to import anything.
If we define a list such as a = [1,2,3]
, then type(a)
will return <class 'list'>
, which means it will be created by built-in list
.
The List
is useful for annotating return types. For example, a function signature using Python3: def threeSumClosest(self, nums: List[int], target: int) -> int:
from https://leetcode.com/problems/integer-to-roman/.
I’m really unsure why this isn’t working. Here is the important part of the code (it’s from a leetcode challenge).
The first line throws the NameError.
def totalFruit(self, tree: List[int]) -> int:
pass
If I try importing List
first I get an error No module named 'List'
. I’m using Python 3.7.3 from Anaconda.
To be able to annotate what types your list should accept, you need to use typing.List
from typing import List
So did you import List
?
Update
If you’re using Python > 3.9, see @Adam.Er8’s answer
To be able to specify a list of str’s in a type hint, you can use the typing
package, and from typing import List
(capitalized, not to be confused with the built-in list
)
Since Python 3.9, you can use built-in collection types (such as list
) as generic types, instead of importing the corresponding capitalized types from typing
.
This is thanks to PEP 585
So in Python 3.9 or newer, you could actually write:
def totalFruit(self, tree: list[int]) -> int: # Note list instead of List
pass
without having to import anything.
If we define a list such as a = [1,2,3]
, then type(a)
will return <class 'list'>
, which means it will be created by built-in list
.
The List
is useful for annotating return types. For example, a function signature using Python3: def threeSumClosest(self, nums: List[int], target: int) -> int:
from https://leetcode.com/problems/integer-to-roman/.