Browse
Core Data Structures
Lists, tuples, dicts, and sets — their underlying implementations and when each is the right choice.
What it is
Python's four built-in containers cover most needs: list (mutable, ordered, O(1) index/append, O(n) insert/delete elsewhere), tuple (immutable, ordered — hashable if its contents are, so usable as a dict key), dict (hash map, O(1) average get/set by key, insertion-ordered since 3.7), set (hash-based, O(1) average membership test, no duplicates).
Choosing the right one
- Need order + duplicates + mutation → list.
- Need a fixed, hashable record → tuple.
- Need fast lookup by key → dict.
- Need fast membership testing or deduplication → set.
Common pitfalls
- Mutable default arguments (
def f(x=[])) are created once and shared across calls — useNoneand initialize inside the function instead. - Dict/set require hashable keys — a list can't be a dict key or set member, but a tuple can.
Why it's the starting point
Every other Python pattern — comprehensions, generators, decorators — is built on comfortably reasoning about which container to reach for and its complexity characteristics.
