9 · for, range, enumerate & zip
Iterate over any sequence, pair items from two lists, and attach indices — the patterns every training loop uses.
Python's `for` loop iterates over any iterable directly — you rarely need an index counter.
Without this:
Without `for`, every repeated operation has to be written out by hand — you can't process a dataset with 1 000 000 rows, let alone run 100 epochs.
Python's for loop binds a name to each element of an iterable in turn. Strings, lists, tuples, sets, dicts, files, generators — everything that is iterable works. No index arithmetic required.
Python (in browser)
`float('inf')` is a sentinel that any real loss will beat on the first comparison — a clean pattern for tracking running minima.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
range(stop) generates integers [0, stop). The three-argument form range(start, stop, step) is the general version — step can be negative for countdown loops.
Python (in browser)
Epoch loops always start from 1 for human-readable logs — use `range(1, n_epochs + 1)` rather than adding 1 inside the print.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
Python (in browser)
`enumerate` unpacks as `(index, value)` pairs. The `start=` keyword lets you begin counting from any integer.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
Python (in browser)
`zip` stops at the shortest sequence. Use `itertools.zip_longest` if you need to pair lists of unequal length without dropping elements.
Python runs entirely in your browser via Pyodide (~6 MB on first Run, cached after).
What does `list(range(2, 10, 3))` return?
Apply range, enumerate, and zip in the Arena — the challenge builds a mini batch iterator.
- `for x in iterable` is the idiomatic Python loop — no index arithmetic, no off-by-one errors.
- `range(start, stop, step)` generates integer sequences on demand without allocating a list.
- `enumerate` gives you index + value; `zip` pairs elements from two iterables. Both return lazy iterators.
Training loops run `for epoch in range(n_epochs)` — `range` controls how many passes over the data. PyTorch DataLoaders are consumed with `for i, (inputs, labels) in enumerate(loader)` where `enumerate` gives the batch index for logging. `zip(feature_names, coef_)` pairs sklearn coefficient arrays with their column names for a readable feature-importance table.
If you remove it: Without `for` + `range`, there is no training loop — a model could only process a single batch. Without `enumerate`, logging batch progress requires a manual counter that is easy to forget to increment. Without `zip`, pairing feature names to learned weights requires awkward index slicing.