10.19 Hands-on Exercises
Inventory Manager A small class wrapping a list to manage a collection of items with add/remove/list operations. class InventoryManager: def …
Inventory Manager A small class wrapping a list to manage a collection of items with add/remove/list operations. class InventoryManager: def …
Conceptual Questions What’s the difference between a list and a tuple? Why is list.append() O(1) amortized but list.insert(0, x) O(n)? …
Readable Code Prefer a list comprehension over an equivalent manual for + .append() loop when it stays short and clear — but fall back to a …
Index Errors Accessing an index that doesn’t exist — especially easy off-by-one mistakes near a list’s boundaries. >>> …
Lists and File Handling Lists are the natural in-memory representation of file contents — one element per line or row. Iterating an open …
Reverse def reverse_list(l): return l[::-1] >>> reverse_list([1, 2, 3]) [3, 2, 1] Remove Duplicates (Order-Preserving) …
Time Complexity Operation Complexity Notes l[i] (index) O(1) Direct memory offset l.append(x) O(1) amortized Spare capacity absorbs most …
sort() vs. sorted() sort() sorts a list in place, returning None — use when the original order doesn’t need to be preserved. sorted() …
The general mechanics of assignment, shallow copy, and deep copy are covered in depth in 6.5 Copying Objects — this page focuses on …
flowchart TD M["matrix"] --> R0["row 0: [1, 2, 3]"] M --> R1["row 1: [4, 5, 6]"] M --> R2["row 2: [7, 8, 9]"] matrix[1][2] → 6 — the first …
Traversing for The standard, most Pythonic way to iterate — no manual index bookkeeping needed. >>> for x in [1, 2, 3]: ... …
These are called as len(l), not l.len() — global functions, not methods, the same distinction covered for strings in 9.8 String Functions. …
flowchart TD LM["list methods"] LM --> ADD["Add\nappend, extend, insert"] LM --> REM["Remove\nremove, pop, clear"] LM --> QRY["Query\nindex, …
+ (Concatenation) Concatenates two lists into a brand-new list — neither original list is modified. >>> [1, 2] + [3, 4] [1, 2, 3, …
remove() Removes the first occurrence of a given value (not a position) — raises ValueError if the value isn’t present. >>> l …
All of these mutate the list in place — the list’s identity (id()) stays the same throughout; see 10.11 Copying and Mutability. Update …
Indexing flowchart LR A["10\n0 / -5"] --- B["20\n1 / -4"] --- C["30\n2 / -3"] --- D["40\n3 / -2"] --- E["50\n4 / -1"] Positive indices count …
Empty Lists The starting point for building up a collection incrementally, e.g. inside a loop. >>> items = [] >>> items [] …
What Is a List? What Is It? An ordered, mutable collection that can hold any mix of values, written with square brackets and …