A container annotation can describe both the outer container and the values inside it. These examples use Python 3.10 or newer throughout this chapter; built-in generic containers such as list[str] require Python 3.9 or newer.
def summarize(names: list[str], counts: dict[str, int]) -> tuple[str, int]:
first = names[0]
return (first, counts[first])
names: list[str] = ["cedar", "pine", "cedar"]
unique: set[str] = set(names)
counts: dict[str, int] = {"cedar": 2, "pine": 1}
print(summarize(names, counts))
print(len(unique))
('cedar', 2)
2
list[str] describes a list of strings; set[str] describes a set of strings. A set removes duplicates and does not promise a useful display order. dict[str, int] describes string keys and integer values. tuple[str, int] describes exactly two positions, in that order; tuple[int, ...] instead describes any number of integer positions. A bare list or dict omits the element information, which can be useful when details are unknown but gives tools less to work with.
The function above assumes a nonempty list and that its first name is a key in counts; hints alone do not express or enforce either condition. Dictionary keys must be hashable; strings and integers are common choices.
Nested types read from outside inward:
routes: dict[str, list[str]] = {"east": ["park", "station"], "west": ["market"]}
print(routes["east"][1])
station
Each key is text; each associated value is a list of text. More complex shapes can be useful, but use names and smaller functions to keep them readable.