Type hints let a function or variable's expected type be documented directly in the code, as already seen with Function Annotations. Generics extend this to container types — expressing not just "this is a list" but "this is a list of integers specifically," giving type checkers much more precise information to verify against.
#how it works
1
Basic type hints annotate simple values
def greet(name: str) -> str documents both an argument and a return type.
2
list[int] specifies the contents
Not just any list, but specifically one containing integers.
3
dict[str, int] specifies both parts
A dictionary with string keys and integer values, precisely.
4
str | None allows an absence
A value that’s either a string, or specifically nothing at all.
5
A type checker reads all of this
Tools like mypy catch mismatches before the code runs — Python itself still enforces none of it at runtime.
#example
def total_score(scores: list[int]) -> int:
return sum(scores)
def get_name(user_id: int) -> str | None:
users = {1: "Ada", 2: "Grace"}
return users.get(user_id)
print(total_score([10, 20, 30]))
print(get_name(1))
print(get_name(99))
Output
60
Ada
None
1scores: list[int] documents that total_score expects a list containing integers specifically, not just any list.
2-> str | None on get_name documents that it might return a string, or might return None if the user_id isn’t found.
3get_name(1) finds a match and returns "Ada"; get_name(99) has no match, and users.get() returns its default, None, exactly as the type hint predicted.
#use cases
Documenting precisely what a function expects and returns, beyond what a basic annotation alone conveys
Catching type-related bugs before running the code at all, using a type checker like mypy in a development workflow
Making a large codebase easier to navigate, since an editor can offer much more accurate autocomplete with precise types
Communicating a function's contract clearly to anyone else (or a future version of yourself) reading the code later
Practice Python interview questions
Every Python lesson maps to the matching interview topic, with answers written for current Python versions.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses →Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free →Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books →