Data Structures: Lists, Tuples & Dictionaries
An authoritative reference manual on dynamic array list allocation, list comprehensions, tuple packing/unpacking, dictionary hash table C-architecture, open addressing collision resolution, dict comprehensions, and sets.
Python features versatile built-in container data structures. This chapter provides a theoretical deep dive into list dynamic array growth, tuple immutability, dictionary hash table architecture, collision resolution mechanisms, set mathematical operations, and comprehensions.
6.1. 1. Lists & Tuples Mechanics
Definition: Lists are dynamic contiguous mutable arrays; Tuples are fixed-size immutable arrays.
Core Working Principles:
- List Dynamic Array Allocation: CPython allocates lists as contiguous arrays of `PyObject` pointers. Uses an over-allocation growth pattern ($0, 4, 8, 16, 25, 35, 46, \dots$) guaranteeing $O(1)$ amortized time complexity for `append()` operations.
- List Methods & Slicing: `append()`, `extend()`, `insert()`, `remove()`, `pop()`, `sort()`, `reverse()`, `index()`, `count()`. Multi-dimensional nested list indexing (`matrix[r][c]`).
- List Comprehensions: Syntactic sugar executing faster than explicit loops: `[expression for item in iterable if condition]`.
- Tuples: Fixed-size immutable arrays requiring less RAM than lists. Immutable and hashable (usable as dict keys). Single-element tuples require trailing commas `(x,)`. Supports tuple packing and unpacking (`a, b = point`).
# List Comprehension Filtering & Squaring Even Numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = [x**2 for x in numbers if x % 2 == 0]
# Tuple Packing & Unpacking
point = (10, 20, 30)
x_coord, y_coord, z_coord = point # Unpacking
print(f"Even Squares: {even_squares}")
print(f"Coords: X={x_coord}, Y={y_coord}, Z={z_coord}")
5-Marks Exam Scoring Points
- Lists use over-allocation to achieve O(1) amortized append operations.
- Tuples are immutable and hashable, usable as dictionary keys.
- Single element tuples require a trailing comma (e.g. t = (5,)).
6.2. 2. Dictionary Hash Table Architecture & Mapping Operations
Definition: Dictionaries are key-value mapping structures optimizing O(1) average-time lookups using an internal C hash table with open addressing collision resolution.
Core Working Principles:
- Dictionary Hash Table C-Architecture:
- • Hash Code Calculation: Key must be **hashable** (its `hash(key)` value is constant).
- • Bucket Index Calculation: `index = hash(key) % array_size`.
- • Collision Resolution: Uses **Open Addressing with Pseudo-Random Probing** (`i = (5*i + 1 + perturb) % array_size`) to resolve hash collisions.
- Dictionary Methods: `keys()`, `values()`, `items()`, `update()`, `pop()`, `popitem()`, `clear()`. Safe retrieval: `dict.get(key, default)` avoids `KeyError`.
- Dictionary Comprehensions & Sets: `{key_expr: val_expr for item in iterable}`. Sets enforce unique hashable elements supporting mathematical operations (union `|`, intersection `&`, difference `-`).
| Data Structure | Mutability | Ordering | Duplicates Allowed? | Primary Use Case |
|---|---|---|---|---|
| List | Mutable | Ordered | Yes | Sequential ordered collections |
| Tuple | Immutable | Ordered | Yes | Fixed record structures & dict keys |
| Dictionary | Mutable | Insertion Ordered | Keys: No / Values: Yes | Fast O(1) key-value mapping lookups |
| Set | Mutable | Unordered | No (Unique only) | Mathematical set operations & deduplication |
5-Marks Exam Scoring Points
- Dictionary keys must be immutable, hashable objects.
- dict.get(key, default) avoids KeyErrors by returning a default fallback.
- Dictionary comprehensions build key-value mappings dynamically.
✍️ Chapter 6 Reference Exercises & Review Problems
words = ['apple', 'banana', 'apricot', 'cherry', 'blueberry']
# Dictionary grouping by initial letter
grouped = {w[0]: [word for word in words if word.startswith(w[0])] for w in words}
print(grouped)
# Output: {'a': ['apple', 'apricot'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
Dictionary key lookups rely on **Hash Tables**. A dictionary key MUST be **hashable** (its hash code computed by `hash()` must remain constant throughout its lifetime).
- **Tuples** are immutable; their internal values cannot change, making them hashable and valid as dictionary keys.
- **Lists** are mutable; their elements can be modified in-place, which would alter their hash value and corrupt the dictionary hash table layout. Therefore, lists are unhashable and raise a `TypeError` if used as dict keys!