Legends ofPythos
Claim your name
Pythonic Python

Type hints

Lesson 9 of 12

Watch the lesson1:01 · with Sigrid
Mental model: Think of type hints as a job description stapled to every function signature. You do not need to open the office door (read the code) to know who works there and what they produce. The hint says: "This role takes two integers and hands back one integer." It is a promise about shape, not value.
Why it matters: In real programs like inventory trackers or sensor dashboards, you often pass data between many functions. Without hints, passing the wrong kind of value (a string where a number belongs) might slide through until the app crashes at 3 AM. Hints let your editor flag that mismatch while you are still writing.
def add(a: int, b: int) -> int:
    return a + b

print(add(2, 3))
a and b should be ints; the result is an int.
The syntax is straightforward. After each parameter name, place a colon and its type. After the closing parenthesis, use an arrow (->) to declare the return type.

These hints are documentation. Python does not enforce them at runtime. If you call add('two', 'three'), it will still run and return 'twothree', but your editor can warn you before you hit Enter.

Modern collection syntax

def first_even(numbers: list[int]) -> int | None:
    for n in numbers:
        if n % 2 == 0:
            return n
    return None

call1 = first_even([3, 7, 8])   # returns 8
call2 = first_even([1, 5, 9])   # returns None
list[int] means a list of ints. int | None means an int or nothing.
Since Python 3.9 you can write built-in collection types directly:
  • list[str] — a list of strings.
  • dict[str, int] — keys are str, values are int.
  • set[float], tuple[int, ...]
For "this might be missing" use the union syntax: str | None. It reads as string or none.
def lookup(user_id: str) -> dict[str, list[int]]:
    data = {'alice': [10, 20], 'bob': [30]}
    return {user_id: data.get(user_id, [])}

scores = lookup('alice')   # {'alice': [10, 20]}
dict[str, list[int]] — a mapping of names to lists of ints.

Your turn

0 of 2 solved

Exercise 1

+35 XP
Write a function word_lengths that takes a list of strings and returns a dictionary mapping each word to its length. Use type hints: the parameter is list[str], the return value is dict[str, int]. Every key must appear in the result.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+35 XP
Write a function find_user that takes a list of user dictionaries (each has keys 'name' and 'active') and the name to search for (which may be None). If the matching user is active, return their name as a string; otherwise return None. Use type hints: parameter 1 is list[dict[str, object]], parameter 2 is str | None, and the return type is str | None.
Write your Python here.

Run your code to check it against the tests.