Describe Collection Elements and Callbacks
Core idea
Built-in generics such as list[int] (Python 3.9+) describe element types. Use collections.abc.Sequence[str] when a read-only sequence interface is enough, rather than requiring list. Callable[[int], str] describes a callback accepting one positional integer and returning text. These are static contracts, not recursive runtime validators.
from collections.abc import Sequencedef first_label(labels: Sequence[str]) -> str: return labels[0] if labels else '-'print(first_label(['A', 'B']))print(first_label(('C', 'D')))The contract needs indexing and length, not mutation.
Apply a callback
from collections.abc import Callabledef convert(values: list[int], fn: Callable[[int], str]) -> list[str]: return [fn(n) for n in values]def label(n: int) -> str: return f'R{n}'print(convert([2, 5], label))The result list contains the callback results.
Common mistake
Sequence does not promise that the underlying object is immutable. isinstance(value, list[int]) is invalid; validate a list and its elements separately if needed.
Practice
Change convert to accept Sequence[int] and try a tuple; keep the callback contract unchanged.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Collection and callable types
Check your understanding of collection and callable types.
What is printed?
def total(xs: list[int]) -> int: return sum(xs)print(total([2, 3]))What is printed?
from collections.abc import Callabledef apply(f: Callable[[int], str]) -> str: return f(4)print(apply(str))Which annotation describes a read-only sequence interface?
Does list[int] enforce every element at runtime?