Data structures
Data Structures
Section titled “Data Structures”Built-In
Section titled “Built-In”xs = [1, 2, 3] # list — ordered, mutable (dynamic array)t = (1, 2) # tuple — ordered, immutabled = {"a": 1, "b": 2} # dict — key–value; insertion order preserved (3.7+)s = {1, 2, 3} # set — unordered, unique, hashable elements onlyf = frozenset({1, 2}) # frozenset — immutable setname = "hello" # str — immutable character sequenceb = b"bytes" # bytes — immutable; bytearray — mutableEmpty: [] list, {} dict, set() set (not {} — that’s a dict).
When to Use What
Section titled “When to Use What”| Use case | Structure |
|---|---|
| Ordered sequence you need to change | list (append, insert, remove) — default for “a sequence of things” |
| Ordered sequence that shouldn’t change | tuple (return values, dict keys, coordinates) |
| Look up by key | dict (names → values, id → record) |
| Unique items or fast “is x in here?” | set (order doesn’t matter, no duplicates) |
| Queue or stack from both ends | deque (use instead of list when you pop from the front often, e.g. BFS) |
| Smallest item, priority queue, “top K” | heapq (min-heap) |
List: create, read, update, delete
Section titled “List: create, read, update, delete”Lists are ordered and mutable. Typical operations:
fruits = ["apple", "banana", "cherry"]
# Create — add elementsfruits.append("mango") # endfruits.insert(1, "blueberry") # at index 1print("After Create:", fruits)
# Read — index or iterateprint("Index 0:", fruits[0])print("All fruits:", fruits)
# Update — assign by indexfruits[3] = "grape"print("After Update:", fruits)
# Delete — by value or by indexfruits.remove("banana") # first matching valuepopped = fruits.pop(0) # index; returns the itemprint("After Delete:", fruits)print("Popped item:", popped)Example output:
After Create: ['apple', 'blueberry', 'banana', 'cherry', 'mango']Index 0: appleAll fruits: ['apple', 'blueberry', 'banana', 'cherry', 'mango']After Update: ['apple', 'blueberry', 'banana', 'grape', 'mango']After Delete: ['blueberry', 'grape', 'mango']Popped item: appleKey points: remove(x) drops the first x and errors if missing. pop(i) removes the item at i and returns it; pop() removes the last item.
Dictionary: create, read, update, delete
Section titled “Dictionary: create, read, update, delete”Dicts map keys to values. Keys must be hashable (e.g. str, int, tuple of immutables).
employee = {"name": "Alex", "role": "SRE", "level": "Senior"}
# Create — new keyemployee["company"] = "ExampleCorp"print("After Create:", employee)
# Read — subscript or .get() for a defaultprint("Name:", employee["name"])print("Dept:", employee.get("department", "N/A"))
# Update — reassign keyemployee["level"] = "Staff"print("After Update:", employee)
# Delete — del or .pop()del employee["company"]removed = employee.pop("level", None)print("After Delete:", employee)print("Removed value:", removed)
print("\nKey-Value pairs:")for key, value in employee.items(): print(f" {key}: {value}")Example output:
After Create: {'name': 'Alex', 'role': 'SRE', 'level': 'Senior', 'company': 'ExampleCorp'}Name: AlexDept: N/AAfter Update: {'name': 'Alex', 'role': 'SRE', 'level': 'Staff', 'company': 'ExampleCorp'}After Delete: {'name': 'Alex', 'role': 'SRE'}Removed value: Staff
Key-Value pairs: name: Alex role: SREKey points: d[key] raises KeyError if key is missing; d.get(key, default) does not. d.pop(key, default) returns default when the key is absent.
For patterns on lists of dictionaries (filtering, grouping, aggregations), see Records and iteration.
Mutability and Hashability
Section titled “Mutability and Hashability”The rule you’ll hit first: You cannot use a list as a dict key or put a list inside a set. If you need something list-like in those places, use a tuple instead.
Why? Dict keys and set members must be hashable. Hashable means Python can turn the value into a stable number (a hash) and use that number to find the key or check membership quickly. If the value could change later (like a list), the hash would no longer match, so Python only allows values that don’t change — i.e. immutable types like tuple, str, or numbers. A list can change (append, remove), so it isn’t hashable; a tuple can’t change, so it is.
Mutable = you can change it after creation (e.g. append to a list, add to a dict). Immutable = you cannot change it; you’d create a new value instead (e.g. tuple, string, numbers).
Mutable types: list, dict, set. Immutable types: tuple, str, frozenset, int, float.
Standard Library and Third-Party
Section titled “Standard Library and Third-Party”- collections:
deque(double-ended queue),defaultdict,Counter,OrderedDict,namedtuple - heapq: min-heap on a list
- queue:
Queue,LifoQueue,PriorityQueue(thread-safe) - array: typed arrays
Third-party: NumPy, Pandas, and graph/tree libs for specialized needs.
Why This Matters for Algorithms
Section titled “Why This Matters for Algorithms”These structures are the base you’ll use when learning algorithms:
- list — dynamic array (indexing, sorting, DP)
- dict — O(1) lookup and graph adjacency
- set — visited sets and uniqueness
- tuple — immutable pairs (edges, coords)
- deque — BFS and queues
- heapq — Dijkstra and heaps
See the Algorithms section for more.