Library

Volume 3 · Python Deep Dive

Notebook
Sign in

Section 8

Data Structures Internals (list as dynamic array, dict as hash table, set internals, time complexity table)

823 words · about 4 min

8.1 Lists — Dynamic Arrays

Python lists are contiguous arrays of pointers to objects, over-allocated for amortized O(1) append (growth pattern roughly new_size = old_size + (old_size >> 3) + 6).

Operation Average Worst Notes
lst[i] O(1) O(1) Direct pointer arithmetic
lst.append(x) O(1)* O(n) Amortized — occasional resize
lst.insert(0, x) O(n) O(n) Shifts all elements right
lst.pop() O(1) O(1) Remove last
lst.pop(0) O(n) O(n) Shifts all elements left
x in lst O(n) O(n) Linear scan
lst.sort() O(n log n) O(n log n) Timsort

8.2 Tuples

Tuples are immutable, fixed-size records ((name, age, dept)) rather than “immutable lists.” CPython caches small tuples (up to length 20) in a free list, making them faster to create and ~27% smaller than an equivalent list. Tuples are hashable only if all their elements are hashable — (1, 2, [3, 4]) is a valid tuple but raises TypeError if used as a dict key or hashed, because it contains a mutable list.

8.3 Dicts — Hash Table Internals

Since Python 3.6 (guaranteed since 3.7), dicts use a compact representation: a sparse indices array (small integers) plus a dense entries array (hash, key, value in insertion order) — giving insertion-order iteration, ~20-25% memory savings versus the old sparse-table design, and better cache locality.

dict[key] lookup:
1. Compute hash(key)
2. index = hash(key) % table_size
3. If slot empty → KeyError
4. If slot.key == key → return slot.value
5. If collision → probe next slot via open addressing (perturbation)
6. Repeat until found or empty
Operation Average Worst
d[key] O(1) O(n)
d[key] = value O(1) O(n) — amortized, resize on 2/3 load factor
del d[key] O(1) O(n)
key in d O(1) O(n)
Iteration O(n) O(n)

Load factor threshold is 2/3; when exceeded the table resizes (4x for small dicts, 2x for large ones).

8.4 Sets

Sets share dicts’ hash-table mechanism but store only keys, so membership tests, unions, and intersections are all effectively O(1)/O(n) rather than list’s O(n) linear scans.

Operation Method Operator Time
Membership — x in s O(1)
Union s1.union(s2) s1 | s2 O(len(s1)+len(s2))
Intersection s1.intersection(s2) s1 & s2 O(min(len(s1),len(s2)))
Difference s1.difference(s2) s1 - s2 O(len(s1))
def find_duplicates(lst):
    seen, duplicates = set(), set()
    for item in lst:
        if item in seen:
            duplicates.add(item)
        seen.add(item)
    return duplicates  # O(n) time

8.5 Master Complexity & Decision Table

Operation list tuple dict set deque
Membership in O(n) O(n) O(1) O(1) O(n)
Index [i] O(1) O(1) O(1)* N/A O(n)
Append O(1) N/A O(1) O(1) O(1)
Prepend O(n) N/A N/A N/A O(1)
Hashable? No If contents are No No No
Need ordered collection?
├── Yes → index access + mutability → LIST; immutable → TUPLE; fast append/popleft → DEQUE
└── No  → key-value pairs → DICT; uniqueness → SET/FROZENSET

Interview Q&A — Section 8

Q1: What is the time complexity of membership testing in a list vs a set, and when would you choose each?

A: List membership is O(n) — a linear scan. Set membership is O(1) average via hash table lookup. Choose a set when you need fast repeated membership checks, uniqueness guarantees, or set algebra (union/intersection/difference); choose a list when you need ordering, indexable access, duplicates, or the collection is tiny enough that hash-table overhead isn’t worthwhile.

Q2: Explain how Python dicts maintain insertion order since 3.7. What changed from earlier versions?

A: Pre-3.6 dicts used one sparse hash table where entries lived at scattered hash-derived positions with many empty slots, so iteration order was arbitrary. Since 3.6 (language-guaranteed in 3.7), dicts use a compact representation: a sparse indices array mapping hashes to positions in a dense entries array that stores (hash, key, value) in insertion order with no gaps. This cuts memory ~20-25%, guarantees insertion-order iteration, and improves cache locality — all while keeping O(1) average lookup.

Q3: Why can’t a tuple containing a list be used as a dictionary key?

A: Dictionary keys must be hashable, and hashability requires that the hash value never change during the object’s lifetime. A tuple’s own immutability doesn’t extend to its elements — t[2].append(5) is legal even though t[0] = 99 isn’t. Since a list is mutable and thus unhashable, any tuple containing one is unhashable too: hash((1, 2, [3, 4])) raises TypeError. A tuple is only hashable if every element it contains is hashable.

Q4: How would you implement an LRU cache using only Python’s built-in data structures?

A: OrderedDict gives you exactly the primitives needed: move_to_end(key) marks an entry as recently used in O(1), and popitem(last=False) evicts the least-recently-used entry in O(1).

from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.cache = OrderedDict()

    def get(self, key):
        if key not in self.cache:
            return -1
        self.cache.move_to_end(key)
        return self.cache[key]

    def put(self, key, value):
        if key in self.cache:
            self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.capacity:
            self.cache.popitem(last=False)