Vasu Patel logoVasu Patel
← Python Syntax & DSA Reference
All chapters in this track
  1. 011. Variables, Types & Operators
  2. 022. Strings
  3. 033. Lists
  4. 044. Tuples, Sets & Dicts
  5. 055. Control Flow
  6. 066. Error Handling
  7. 077. Functions & Lambdas
  8. 088. Comprehensions
  9. 099. Built-in Functions
  10. 1010. Type Hints (3.10+)
  11. 1111. Classes & Dataclasses
  12. 1212. Iterators & Generators
  13. 1313. DSA Standard Library
  14. 1414. Python 3.9–3.11 Features for DSA
  15. 1515. DSA Idioms & Gotchas
  16. 1616. Master Quick Reference

Chapter 10 of 16

10. Type Hints (3.10+)

Tutorial

Python 3.10+ introduced X | Y union syntax, replacing Optional[X] and Union[X, Y]. Python 3.9+ allows built-in collection types directly in hints.

# ── Modern type hints (3.9+) ───────────────────────────────────
# No longer need to import from typing for basic types
def process(arr: list[int]) -> dict[str, int]: ...   # 3.9+
def pair(a: tuple[int, int]) -> set[str]: ...        # 3.9+

# ── Union type (3.10+) ─────────────────────────────────────────
# Old (still works):  from typing import Optional; Optional[int]
# New (3.10+):
def search(arr: list[int], target: int) -> int | None:
    ...

def parse(val: str | int | float) -> float:
    return float(val)

# ── Class self-reference ──────────────────────────────────────
class ListNode:
    def __init__(self, val: int = 0, next: "ListNode | None" = None):
        self.val  = val
        self.next = next

# Python 3.11+: typing.Self (more precise than string annotation)
from typing import Self

class TreeNode:
    def __init__(self, val: int = 0,
                 left:  Self | None = None,
                 right: Self | None = None):
        self.val   = val
        self.left  = left
        self.right = right

# ── TypeAlias (3.10+) ─────────────────────────────────────────
from typing import TypeAlias
Graph: TypeAlias = dict[int, list[int]]
Matrix: TypeAlias = list[list[int]]

# ── Common DSA type hint patterns ─────────────────────────────
def bfs(graph: dict[int, list[int]], start: int) -> list[int]: ...
def dijkstra(graph: dict[int, list[tuple[int,int]]], src: int) -> list[int]: ...
def knapsack(wt: list[int], val: list[int], W: int) -> int: ...

Reference

Old syntaxModern (3.9+/3.10+)Version
List[int]list[int]3.9+
Dict[str,int]dict[str,int]3.9+
Tuple[int,int]tuple[int,int]3.9+
Set[str]set[str]3.9+
Optional[int]int | None3.10+
Union[int,str]int | str3.10+
"ListNode" forward refSelf3.11+
TypeAliasfrom typing import TypeAlias3.10+