Type hints basics
- Python course
- Beginner
- Lesson 81/116
- 4 min
Learn type hints like int, str, list.
Type hints basics
A type hint marks the expected type of a parameter and return value:
def add(a: int, b: int) -> int:
return a + bPython does not enforce type hints at runtime; they are only for documentation and static analysis (mypy, pyright). Passing the wrong type still runs.
Type hints are very useful in large projects; they catch wrong usage early.
Common type hints
Common type hints are int, float, str, bool, list, dict. More complex types are written as list[int], dict[str, int]:
def count_words(words: list[str]) -> int:
return len(words)This clearly marks that the function expects a list[int] and returns int. IDEs use this info to give hints.
Practice Write a function with a type hint
Define a function called square with parameter n: int and return type -> int. The body does return n * n. Assign square(5) to result. Then print print(result).
Starter code
# Define the square functionSample solution
def square(n: int) -> int:
return n * n
result = square(5)
print(result)Expected output
25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the type hint
def add(a: ____, b: int) -> int:
return a + b
def add(a: int, b: int) -> int:
return a + b
Explanation: a: int marks the parameter type.
2 What does a type hint do at runtime?
- Slows the code down
- Raises an error on wrong type
- Does nothing; it is for documentation Correct answer
- Compiles the code
Explanation: A type hint does not affect runtime; it is only for documentation and static analysis.
3 Match the type hints
| Term | Meaning |
|---|---|
int |
Integer |
str |
String |
list[int] |
List of integers |
-> int |
Returns int |