Sub topic 4
Annotating lists, dicts, sets, and tuples
This chapter assumes you can write Python functions, know the built-in collection types, and have already seen the basic name: type annotation syntax. You should also be able to run a checker such as mypy or pyright.
Why the element type matters
Writing list tells a checker only that a value is a list. It says nothing about what the list holds. Since Python 3.9 you can parameterize the built-in collection types directly, so list[int] means a list whose items are all int. Older code imports List, Dict, and Set from typing. You don't need those on current Python versions.
| Annotation | Meaning |
|---|---|
| `list[str]` | A list of strings of any length |
| `dict[str, int]` | Keys are `str`, values are `int` |
| `set[int]` | A set of integers |
| `tuple[int, str]` | Exactly two items: an `int`, then a `str` |
| `tuple[int, ...]` | Any number of `int` items |
Lists, dicts, and sets
The element type goes in square brackets. A checker uses it to validate both what you put in and what you take out.
def total_length(words: list[str]) -> int:
return sum(len(word) for word in words)
def count_words(words: list[str]) -> dict[str, int]:
counts: dict[str, int] = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
return counts
def unique_ids(ids: list[int]) -> set[int]:
return set(ids)
print(total_length(["a", "bb"]))
print(count_words(["a", "b", "a"]))
print(unique_ids([1, 2, 2, 3]))The annotation on counts is needed. Without it, a checker cannot infer the types from an empty {} and may ask you to add one.
Tuples are different
A tuple usually has a fixed length, and each position can have its own type. So tuple[int, str] describes exactly two items. To describe a tuple of any length with one item type, write tuple[int, ...].
def parse_pair(text: str) -> tuple[str, int]:
name, number = text.split("=")
return name, int(number)
def total(values: tuple[int, ...]) -> int:
return sum(values)
key, value = parse_pair("age=30")
print(key, value)
print(total((1, 2, 3, 4)))Common errors
- Invariance of
list. Alist[bool]is not accepted wherelist[int]is expected, even thoughboolis a subtype ofint. The function could append anintto the list and break the caller's guarantee. - Wrong tuple length.
tuple[int, int]rejects a three-item tuple. If the length varies, usetuple[int, ...]. - Mixed contents.
[1, "a"]is inferred aslist[object]or flagged as an error, depending on the checker. Use a union such aslist[int | str]if you want mixed contents.
def show(items: list[int | str]) -> None:
for item in items:
print(item)
show([1, "a", 2])Exercise
What is the difference between tuple[int, str] and tuple[int, ...]?
Show answer
tuple[int, str] is a tuple of exactly two items, an int followed by a str. tuple[int, ...] is a tuple of any length whose items are all int.
Exercise
Write the return annotation for a function that returns a dictionary mapping each name (str) to a list of scores (int).
Show answer
dict[str, list[int]]