Volume 02 Vectors were ordered sequences of numbers. Python lists are the native ordered, mutable sequence—the first structure you use to hold feature rows, label columns, epoch losses, and experiment metrics before graduating to NumPy arrays.
Lists bridge math and code: a feature vector [1.2, 0.5, 3.1] is a list of floats; a batch is a list of such lists. Master indexing and slicing here—the same ideas apply to tensors later.
Learning Objectives
By the end of this lesson, students should be able to:
- Create lists with literals,
list(), and list comprehensions. - Access elements by index and slice sub-sequences with
[start:stop:step]. - Modify lists: append, extend, insert, and pop.
- Build a list of numeric features for a single training sample.
- Iterate lists with loops and common methods (
len,sum,min,max). - Understand negative indexing and half-open slice intervals.
Creating and Inspecting Lists
A list is an ordered, mutable collection of objects enclosed in square brackets. Elements can be mixed types, though ML code typically uses homogeneous lists of numbers or nested lists for tabular data.
Indexing and Slicing
Indices start at 0. Negative indices count from the end: -1 is the last element. Slices use [start:stop] where stop is exclusive.
| Expression | Result (on [10, 20, 30, 40, 50]) |
Meaning |
|---|---|---|
arr[0] |
10 |
First element |
arr[-1] |
50 |
Last element |
arr[1:3] |
[20, 30] |
Index 1 up to (not including) 3 |
arr[:3] |
[10, 20, 30] |
First three elements |
arr[::2] |
[10, 30, 50] |
Every second element |
List of Features: Engineering Pattern
A single ML sample is often a list of features—fixed-order numeric or categorical values. Consistent ordering is critical: index 0 must always mean the same feature across all samples.
Feature List (Python)
[1850, 3, 12, 1]- Positional meaning by convention
- Good for prototyping
- Document column order separately
Named Access (Later)
- Dictionaries with feature names
- Pandas DataFrame columns
- Self-documenting schemas
- Preferred at production scale
Mutating Lists
| Method | Effect | ML Example |
|---|---|---|
append(x) |
Add one element at end | Log new epoch loss |
extend(iterable) |
Add all elements | Merge batch results |
insert(i, x) |
Insert at index | Pad sequence (rare) |
pop(i) |
Remove and return | Deque for streaming buffer |
Common Misconceptions
Why people believe it: Assignment syntax looks mutating.
Reality: Slicing creates a new list. subset = data[:5] leaves data unchanged unless you assign to a slice: data[:5] = [].
Why people believe it: Both hold ordered numbers.
Reality: Lists are flexible Python objects; NumPy arrays are homogeneous, fixed-type, and support vectorized math. Convert with np.array(my_list) when doing linear algebra.
Why people believe it: Everyday counting starts at 1.
Reality: Python is zero-indexed. The first feature is features[0].
Quick Knowledge Check
- Short Answer: Index of first element? Answer: 0.
- True/False:
arr[1:4]includes index 4. Answer: False — stop is exclusive. - Multiple Choice:
arr[-1]returns: (a) first, (b) last, (c) error, (d) empty list. Answer: (b). - Short Answer: Difference between
appendandextend? Answer: append adds one item; extend adds all items from iterable. - True/False: Lists are mutable. Answer: True.
- Computation:
[10,20,30,40][1:3]equals? Answer: [20, 30]. - Short Answer: Why document FEATURE_NAMES alongside feature lists? Answer: Positional lists lack self-describing keys.
- True/False: List comprehensions create new lists. Answer: True.
- Multiple Choice: Volume 02 vector [1,2,3] maps to Python: (a) dict, (b) list, (c) set, (d) tuple only. Answer: (b) list (or tuple).
- Short Answer: How to get last three losses from
losses? Answer: losses[-3:].
Key Takeaways
- Lists are ordered, mutable sequences—Python’s default container for sample rows and metrics history.
- Zero-based indexing and half-open slices
[start:stop]select elements and subsequences. - A feature vector is a fixed-order list of values; document column meaning explicitly.
append,extend, and comprehensions build and transform lists efficiently.- Lists prototype data; NumPy arrays scale computation (Module 3.3).
- Next: Dictionary for named key-value access.
Hands-on idea: Store 5 epochs of losses in a list; slice train vs validation portions; plot mentally which slice improves faster.
Whiteboard exercise: Draw indices 0–4 under a feature list and mark slices [:2], [2:], [-1].
Discussion prompt: When does a list of lists become unwieldy compared to a CSV or DataFrame?