← Master Index
Vol. 03 Module 3.1 Lecture

Lists

Python Basics

How This Lesson Fits the Module

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

Definition — List

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.

# Feature vector for one house: [sq_ft, bedrooms, age] sample_features = [1850, 3, 12] # Dataset: list of feature lists dataset = [ [800, 2, 5], [1200, 3, 8], [1850, 3, 12], ] # List of epoch losses from training epoch_losses = [0.92, 0.71, 0.55, 0.48, 0.44] print(len(epoch_losses), min(epoch_losses), max(epoch_losses))

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
losses = [0.92, 0.71, 0.55, 0.48, 0.44] # Train/validation split by index slice train_losses = losses[:3] # first 3 epochs val_losses = losses[3:] # remaining epochs # Last recorded loss final_loss = losses[-1] # Feature subset: first two columns only row = [1850, 3, 12, 1] # sq_ft, beds, age, has_garage subset = row[:2] # [1850, 3]

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
FEATURE_NAMES = ["sq_ft", "bedrooms", "age_years", "has_garage"] def describe_sample(features): """Pair names with values for debugging.""" return list(zip(FEATURE_NAMES, features)) sample = [1850, 3, 12, 1] print(describe_sample(sample)) # [('sq_ft', 1850), ('bedrooms', 3), ('age_years', 12), ('has_garage', 1)]

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
batch_predictions = [] for pred in [0.1, 0.7, 0.3, 0.9]: batch_predictions.append(pred) # List comprehension — compact transform squared = [x ** 2 for x in batch_predictions]
What’s Next in This ModuleThe next lecture, Dictionary, maps feature names to values—the Python equivalent of JSON configs and keyed metadata.

Common Misconceptions

Misconception 1: “Slicing modifies the original list.”

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] = [].

Misconception 2: “Lists and NumPy arrays are the same.”

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.

Misconception 3: “List index 1 is the first element.”

Why people believe it: Everyday counting starts at 1.

Reality: Python is zero-indexed. The first feature is features[0].

Quick Knowledge Check

  1. Short Answer: Index of first element? Answer: 0.
  2. True/False: arr[1:4] includes index 4. Answer: False — stop is exclusive.
  3. Multiple Choice: arr[-1] returns: (a) first, (b) last, (c) error, (d) empty list. Answer: (b).
  4. Short Answer: Difference between append and extend? Answer: append adds one item; extend adds all items from iterable.
  5. True/False: Lists are mutable. Answer: True.
  6. Computation: [10,20,30,40][1:3] equals? Answer: [20, 30].
  7. Short Answer: Why document FEATURE_NAMES alongside feature lists? Answer: Positional lists lack self-describing keys.
  8. True/False: List comprehensions create new lists. Answer: True.
  9. 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).
  10. 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.
Trainer’s Guide

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?

What’s Next Continue to Dictionary for key-value storage of configs, metrics, and JSON-like API payloads.