0Pricing
Python Academy · Lesson

Complex Types: List, Dict, Optional, Union

Use typing module generics and Optional/Union correctly.

Complex Types: List, Dict, Optional, Union is a free Python Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

typing Module Overview

Before Python 3.9, generic types like List, Dict, Tuple came from typing. Since 3.9 you can use the built-in types directly.

from typing import List, Dict, Tuple, Optional, Union

# Python 3.9+: use list[int], dict[str,int] directly
# Python 3.8-: use typing.List[int], typing.Dict[str,int]

List and Sequence

Use list[T] for mutable sequences and Sequence[T] when accepting any ordered sequence (list, tuple, str).

from typing import Sequence

def total(nums: list[int]) -> int:
    return sum(nums)

def first(items: Sequence[str]) -> str:
    return items[0]   # works with list, tuple, str

Dict and Mapping

Use dict[K,V] for mutable dicts and Mapping[K,V] for read-only dict-like objects.

from typing import Mapping

def lookup(data: Mapping[str, int], key: str) -> int | None:
    return data.get(key)

result = lookup({"a": 1, "b": 2}, "a")
print(result)   # 1

Tuple Annotations

Fixed-length: tuple[int, str, float]. Variable-length: tuple[int, ...].

def point() -> tuple[float, float]:
    return (1.0, 2.0)

def first_n(n: int) -> tuple[int, ...]:
    return tuple(range(n))

# Named tuple with types:
from typing import NamedTuple
class Point(NamedTuple):
    x: float
    y: float

Optional[T]

Optional[T] is shorthand for T | None. Always the right choice when a parameter can be absent.

from typing import Optional

def find_user(user_id: int) -> Optional[dict[str, str]]:
    db: dict[int, dict[str, str]] = {
        1: {"name": "Alice"}
    }
    return db.get(user_id)

Union Types

Union[X, Y] or X | Y (3.10+) for values that may be one of several types.

from typing import Union

def stringify(value: Union[int, float, str]) -> str:
    return str(value)

# Python 3.10+:
def stringify2(value: int | float | str) -> str:
    return str(value)

Literal Types

Literal["a","b","c"] restricts a value to a specific set of literals.

from typing import Literal

Mode = Literal["read", "write", "append"]

def open_file(path: str, mode: Mode) -> None:
    with open(path, mode):
        pass

open_file("data.txt", "read")    # ok
# open_file("data.txt", "exec")  # mypy error

TypedDict

TypedDict annotates dict shapes where each key maps to a specific type.

from typing import TypedDict

class User(TypedDict):
    name: str
    age: int
    email: str | None

def greet(user: User) -> str:
    return f"Hello, {user['name']}"

alice: User = {"name": "Alice", "age": 30, "email": None}

Set and FrozenSet

Annotate sets with set[T] and frozen sets with frozenset[T].

def unique(items: list[int]) -> set[int]:
    return set(items)

def allowed_methods() -> frozenset[str]:
    return frozenset({"GET", "POST", "DELETE"})

Iterable and Iterator

Use Iterable[T] for any object you can loop over; Iterator[T] for objects with __next__.

from typing import Iterable, Iterator

def evens(numbers: Iterable[int]) -> Iterator[int]:
    return (n for n in numbers if n % 2 == 0)

for n in evens([1, 2, 3, 4, 5]):
    print(n)   # 2 4

Any and NoReturn

Any opts out of type checking for a value. NoReturn marks functions that never return (they always raise or loop forever).

from typing import Any, NoReturn

def accept_all(x: Any) -> None:
    print(x)

def crash(msg: str) -> NoReturn:
    raise RuntimeError(msg)   # never returns normally

Quick Check

What does Optional[str] mean?

Recap

Use list[T], dict[K,V], tuple[T,...] for collections. Optional[T] = T | None. Union[X,Y] or X|Y for multiple types. Literal for specific values; TypedDict for typed dict shapes; Any to opt out.

Frequently asked questions

Is the “Complex Types: List, Dict, Optional, Union” lesson free?

Yes — the full text of “Complex Types: List, Dict, Optional, Union” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.

What will I learn in “Complex Types: List, Dict, Optional, Union”?

Use typing module generics and Optional/Union correctly. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Complex Types: List, Dict, Optional, Union” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Basic Type Annotations
  2. Complex Types: List, Dict, Optional, Union
  3. TypeVar, Generic Classes, and Protocol
  4. Running mypy and Fixing Type Errors
← Back to Python Academy