Python Data Structures
Lists, tuples, dicts and sets in depth — internals and time complexity, copying, the collections module (deque, Counter, defaultdict, OrderedDict, namedtuple), heapq, bisect, and dataclasses.
Python's built-in containers are implemented in C and highly optimised. Choosing the right one — and knowing its costs — matters for both performance and interviews.
Complexity cheat sheet
| Operation | list | dict | set | deque |
|---|---|---|---|---|
Index x[i] | O(1) | — | — | O(n) |
| Append / pop at end | O(1)* | — | — | O(1) |
| Insert / pop at front | O(n) | — | — | O(1) |
Membership in | O(n) | O(1) avg | O(1) avg | O(n) |
| Get / set by key | — | O(1) avg | — | — |
| Delete by key/value | O(n) | O(1) avg | O(1) avg | O(n) |
| Sort | O(n log n) | — | — | — |
*Amortised. Average-case dict/set operations can degrade with pathological hashes.
list: a dynamic array
A list stores an array of pointers to objects. It over-allocates (growth factor ~1.125 plus a constant) so append is amortised O(1).
nums = [3, 1, 4]
nums.append(1); nums.extend([5, 9]); nums.insert(0, 2) # insert(0) is O(n)!
nums.pop(); nums.pop(0) # pop(0) is O(n)
nums.remove(4) # first occurrence, O(n)
nums.sort(key=abs, reverse=True) # in place, stable (Timsort)
sorted_copy = sorted(nums) # new list
nums.index(1); nums.count(1)
nums[::2] # every second element (copy)tuple: immutable sequences
point = (3, 4)
single = (5,) # the comma makes the tuple, not the parentheses
x, y = point # unpacking
locations = {(40.7, -74.0): "NYC"} # hashable (if contents are), so usable as dict keysTuples are slightly smaller and faster to create than lists, and signal "fixed structure". For named fields, use namedtuple or a dataclass.
dict: the hash map
Since Python 3.7, dicts preserve insertion order (guaranteed by the language). CPython uses a compact layout: a sparse index table of small integers pointing into a dense array of (hash, key, value) entries — memory-efficient and ordered. Collisions are resolved by open addressing with perturbed probing; the table resizes when two-thirds full.
ages = {"ada": 36, "alan": 41}
ages["grace"] = 85
ages.get("bob") # None instead of KeyError
ages.get("bob", 0)
ages.setdefault("bob", []).append(...) # insert default if missing, return value
ages.pop("alan"); del ages["ada"]
"grace" in ages # O(1) — checks keys
for name, age in ages.items(): ...
merged = defaults | overrides # 3.9+: merge (right wins)
{v: k for k, v in ages.items()} # invertKeys must be hashable: immutable built-ins (str, int, tuple of hashables, frozenset) or objects with consistent __hash__ and __eq__. Mutating a key object's hashed fields after insertion breaks lookups.
set: unique, unordered
seen = set()
seen.add(3); seen.discard(4) # discard doesn't raise if missing
a, b = {1, 2, 3}, {2, 3, 4}
a | b, a & b, a - b, a ^ b # union, intersection, difference, symmetric difference
a <= b # subset?
unique = list(dict.fromkeys(items)) # dedupe while PRESERVING order (set() loses order)
frozenset({1, 2}) # immutable, hashable setConverting a list to a set for repeated membership tests turns O(n) lookups into O(1).
The collections module
from collections import deque, Counter, defaultdict, OrderedDict, namedtuple, ChainMap
# deque: O(1) at both ends — queues, BFS, sliding windows
q = deque([1, 2, 3], maxlen=5) # maxlen: oldest items drop off automatically
q.appendleft(0); q.append(4); q.popleft(); q.rotate(1)
# Counter: counting hashables
words = "the cat and the hat".split()
c = Counter(words) # Counter({'the': 2, 'cat': 1, ...})
c.most_common(2) # [('the', 2), ('cat', 1)]
c["dog"] # 0, not KeyError
Counter("anagram") == Counter("nagaram") # anagram check
# defaultdict: auto-create missing values
graph = defaultdict(list)
for u, v in edges:
graph[u].append(v)
groups = defaultdict(set)
# OrderedDict: still useful for move_to_end / popitem(last=False) — e.g. LRU caches
lru = OrderedDict()
lru["a"] = 1; lru.move_to_end("a"); lru.popitem(last=False)
# namedtuple: lightweight immutable records
Point = namedtuple("Point", "x y")
p = Point(3, 4); p.x; p._replace(x=5)heapq: priority queues
heapq turns a list into a binary min-heap in place:
import heapq
heap = []
heapq.heappush(heap, (2, "write code")) # tuples compare element by element
heapq.heappush(heap, (1, "write spec"))
heapq.heappop(heap) # (1, 'write spec')
heap[0] # peek at the smallest: O(1)
heapq.heapify(nums) # O(n)
heapq.nlargest(3, nums); heapq.nsmallest(3, records, key=lambda r: r.score)
# Max-heap: push negated keys
heapq.heappush(max_heap, (-priority, item))Tie-breaking: if priorities are equal, Python compares the next tuple element — which fails for uncomparable objects. Add a counter: (priority, next(counter), item).
bisect: binary search on sorted lists
import bisect
scores = [10, 20, 30, 40]
bisect.bisect_left(scores, 25) # 2 — insertion point
bisect.insort(scores, 25) # insert keeping order (O(n) due to shifting)
# grade lookup
breakpoints, grades = [60, 70, 80, 90], "FDCBA"
grades[bisect.bisect(breakpoints, 85)] # 'B'Copying
import copy
a = [[1, 2], [3]]
b = a # no copy: same object
c = a.copy() # shallow: new outer list, SAME inner lists (also list(a), a[:])
d = copy.deepcopy(a) # fully independent
c[0].append(99) # also visible in a!dataclasses for structured data
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True) # immutable, hashable, memory-efficient
class Point:
x: float
y: float
@dataclass(order=True)
class Task:
priority: int
title: str = field(compare=False)
tags: list[str] = field(default_factory=list) # never use a mutable default directly
Task(2, "deploy") < Task(3, "test") # True — ordering generated from fieldsslots=True removes the per-instance __dict__, saving memory for many small objects. See OOP & the data model.
Choosing
| Need | Use |
|---|---|
| Ordered, indexable sequence | list |
| Fixed record / dict key | tuple, namedtuple, frozen dataclass |
| Lookup by key | dict |
| Membership / dedupe | set |
| Queue / BFS / both ends | collections.deque |
| Counting | Counter |
| Grouping | defaultdict(list) |
| Smallest/largest repeatedly | heapq |
| Large numeric arrays | array module or NumPy |
- list: O(1) index and append, O(n) front operations and membership.
- dict and set: O(1) average lookups; dicts keep insertion order; keys must be hashable.
- Use deque for queues, Counter for counting, defaultdict for grouping, heapq for priority queues.
- Beware aliasing: [[0]*3]*3 and shallow copies share inner objects.
- dataclasses (frozen, slots) are the modern way to define records.
QHow is a Python dict implemented?hard
As a hash table with open addressing. Modern CPython uses a compact design: a sparse indices array maps hash slots to positions in a dense entries array storing hash, key and value in insertion order. Lookups hash the key, probe slots with a perturbation scheme until finding an equal key or an empty slot, and compare stored hashes before calling eq. The table resizes when it is about two-thirds full, keeping operations O(1) on average.
QWhy is list.pop(0) slow and what should you use instead?easy
A list is a contiguous array of pointers; removing the first element shifts every remaining pointer left, O(n). collections.deque is a doubly linked list of blocks supporting O(1) appends and pops at both ends, so use deque.popleft() for queues.