0Pricing
Python Academy · Lesson

Complex Types: List, Dict, Optional, Union

Use typing module generics and Optional/Union correctly.

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

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