Legends ofPythos
Claim your name
Pythonic Python

Type hints

Lesson 9 of 12

Watch the lesson5:41 ยท with Sigrid
Mental model: A type hint is a label. Like the label on a shelf, it tells you what belongs there without you having to look. Hints on a function's def line say what kind of values go in and what kind comes back, so you don't have to read the whole function to find out. They describe the kind of value, not the value itself.
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 (text 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 bracket, use an arrow (->) to declare the return type.

These hints are documentation. Python doesn't check them when your code runs. 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(nums: list[int]) -> int | None:
    for n in nums:
        if n % 2 == 0:
            return n
    return None

print(first_even([3, 7, 8]))  # 8
print(first_even([1, 5, 9]))  # None
list[int] means a list of whole numbers. int | None means a whole number, or None.
Since Python 3.9, square brackets after list or dict say what's inside:
  • list[str]: a list of text.
  • dict[str, int]: a dictionary with text keys and whole-number values.
  • dict[str, object]: text keys, and values of any kind (object means any kind of value).
  • set[float] and tuple[int, ...] (a tuple of whole numbers, any length) work the same way.
For a value that might be missing, use a vertical bar, which means or: str | None reads as text or None. The bar needs Python 3.10 or newer.
def lookup(name: str) -> dict[str, list[int]]:
    data = {'alice': [10, 20], 'bob': [30]}
    return {name: data.get(name, [])}

print(lookup('alice'))  # {'alice': [10, 20]}
dict[str, list[int]]: a dictionary with text keys, and lists of whole numbers as values.

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 the 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: the first parameter is list[dict[str, object]], the second parameter is str | None, and the return type is str | None. object means any kind of value: here, text or True/False. The def line gets long: inside its round brackets, you can break the line after a comma and carry on, indented, on the next line.
Write your Python here.

Run your code to check it against the tests.