Python Typing Collections
A collection hint names a container and the types inside it. list[int] names whole numbers as the items.
A list hint
The hint names the list and its items. Every item should be a whole number.
scores: list[int] = [10, 20, 30]
print(sum(scores))A dict hint
The first type is for keys. The second type is for values.
ages: dict[str, int] = {"Ada": 36, "Bo": 29}
print(ages["Ada"])A tuple hint
The three dots mean any number of items. Each item is a whole number.
readings: tuple[int, ...] = (4, 8, 15)
print(len(readings))
print(readings[1])A set hint
A set hint names its items too. We sort before printing, because set order is not promised.
tags: set[str] = {"red", "blue"}
print(sorted(tags))A union hint
A union lets one parameter accept two types. The bar reads as the word or.
def show_id(value: int | str) -> None:
print(value)
show_id(7)
show_id("A7")The older Optional spelling
Optional[str] is the older spelling you will meet. It means the same as str | None here.
from typing import Optional
nickname: Optional[str] = None
print(nickname)A nested hint
Read a nested hint from the inside out. The inner hint is a list of whole numbers. The outer hint pairs text keys with those lists.
grid: dict[str, list[int]] = {"Ada": [10, 20], "Bo": [30]}
print(grid["Ada"][1])Example
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
words: list[str] = ["cat", "dog", "cat", "bird", "dog", "cat"]
result: dict[str, int] = count_words(words)
for word in sorted(result):
print(word, result[word])Key points
- Generic: a hint that names a container and the types inside it
- Use list[int] for a list that holds whole numbers
- Use dict[str, int] for text keys paired with whole numbers
- Use tuple[int, ...] for a tuple of whole numbers of any length
- Union: a hint that allows two or more types, written with a | bar
- The | union form needs Python 3.10 or newer
- A plain hint like list says nothing about the items inside.
In this example, count_words takes a list of text. It returns a dict that pairs text with whole numbers. The local counts dict starts empty. Each word adds one to its count. The .get() call uses zero for a new word. The words list holds six short words. The result pairs each word with its count. The loop walks the keys in sorted order. It prints each word with its count.
Note
Older code spells the same idea with Optional and Union.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does dict[str, list[int]] describe?