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]:
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]:
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
Set
, Dict
, Tuple
, Callable
etc.NamedTuple
instead of namedtuple
From Python 3.9 on, one could as well use the standard list
constructor for the type hint, see here.
It's a new feature in version 3.5. You can see the docs.
https://docs.python.org/3.5/library/typing.html