Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 10.2 — Typing Collections, Optional and Unions
Python · Example 3 of 3

Why signatures prefer Iterable and Sequence (and the str trap)

A tag counter for blog posts. A checker accepts the string in the second call, because a str is an Iterable of one-letter strs. The last call shows why a function that changes its list must say list[float]: the checker refuses to pass it a list[int] (a list is invariant), while read-only Sequence[float] accepts one.

Hints for containers say what is inside: list[int], dict[str, int], tuple[int, str]. X | None means "an X, or nothing", and Sequence, Mapping, Iterable and Callable describe what a function needs without demanding one exact class.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write first_or_none(items: list[int]) -> int | None that returns the first item or None for an empty list. Print the result for [7, 8] and [].

02

Write describe(value: int | str) -> str returning "number 5" or "text hi" using isinstance.

03

Write call_twice(fn: Callable[[int], int], x: int) -> int that returns fn(fn(x)) and call it with a lambda that adds 3 to 10.

Explain it without notes

01

How do you write the type of a list of integers, and which Python version made the plain list[int] form possible?

02

What does str | None mean, and how is it different from a parameter with a default value?

03

Why hint a function parameter as Iterable[int] instead of list[int]?

04

What is narrowing?

05

Why does a checker reject passing a list[int] to a function that takes list[float], yet accept it for Sequence[float]?

Why signatures prefer Iterable and Sequence (and the str trap)
Sign in to run this example in your browser.

Expected output

{'python': 2, 'ai': 1}
{'p': 1, 'y': 1, 't': 1, 'h': 1, 'o': 1, 'n': 1}
85.0
[80, 90, 100.0]