19

I want to understand the declaration of this function: ->List[int]:

I have learned the basics of Python and I never saw function declaration like this before

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
2

2 Answers 2

30

It is a so called "type hint" (or "function annotation"; these are available since Python 3.0).

  • -> List[int] means that the function should return a list of integers.
  • nums: List[int], target: int means that nums is expected to be a list of integers and that target is expected to be an integer.

This is not a hard requirement, though, i.e. you can still call the function with objects of different types passed for these parameters and the function can as well return something different than a list of intergers (unlike in other languages like Java where providing wrong types would result in a compile error). To put it differently: Type hints are irrelevant for the program execution, they are ignored at runtime (ignoring the type hints is just the default behavior, but they are available at runtime via __annotations__, so you could do something with them).

Type hints can express the intent of the author and can be checked before program execution by tools like mypy (these can check e.g. that a function is only called with parameters of the correct type and returns something of the correct type).

Note that List is not available in the standard namespace (unlike list), but (at least before Python 3.9) instead needs to be imported from typing which also

  • provides other types for standard types, like Set, Dict, Tuple, Callable etc.
  • allows to define own types
  • provides typed versions of other types, like NamedTuple instead of namedtuple

From Python 3.9 on, one could as well use the standard list constructor for the type hint, see here.

1
  • 2
    I am a newbie and this is an in-depth explanation .thanks man I appreciate it Jun 8, 2019 at 12:14
5

It's a new feature in version 3.5. You can see the docs.
https://docs.python.org/3.5/library/typing.html

Not the answer you're looking for? Browse other questions tagged or ask your own question.