NameError: name 'List' is not defined

Ariel Frischer picture Ariel Frischer · Aug 15, 2019 · Viewed 41.1k times · Source

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.

Answer

LaundroMat picture LaundroMat · Aug 15, 2019

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