PythiloLesson 9 of 9 · progress kept in this browser

Typing

Annotations describe what a function expects. Python does not enforce them at runtime. Tools such as type checkers and editors read them, and so do people.

def lengths(
    words: list[str],
) -> dict[str, int]:
    return {w: len(w) for w in words}
  • list[str], dict[str, int] and tuple[int, int] describe contents.
  • int | None means either one.
  • type UserId = int creates a named alias.
Your task

Add exact annotations: word_lengths(words: list[str]) -> dict[str, int], and make first_or_none generic with a type parameter T, taking items: list[T] and returning T | None. Define the alias type Scores = dict[str, int]. Fix first_or_none so that it returns None for an empty list.

All lessons