Use enumerate to preserve positions

Type one expression at a time and check its delimiters. · 193 words

When an experiment processes many examples, keep each example's position in the original data. Python's enumerate(iterable) produces an index-item pair for every item. The index starts at 0 unless you supply another start value. For example, temperatures = [18.5, 21.0, 19.5] yields (0, 18.5), (1, 21.0), and (2, 19.5). You can unpack each pair with for position, temperature in enumerate(temperatures):. The position is metadata: it does not change the measurement or become part of the temperatures list. This helps when reporting a measurement, labeling a plot, or tracing a surprising model result to its source row.

A second experiment may prefer labels that match a written log. Use enumerate(steps, start=1), where steps = ["collect", "clean", "train"]. The loop receives (1, "collect"), (2, "clean"), and (3, "train"), which are easier to read than zero-based numbers. enumerate works with any iterable, not only lists, and it does not modify the source. It also creates each pair only when the loop needs it, so it avoids building a second list of pairs. If you sort or filter the data first, enumerate the final sequence. Its positions then refer to that new order, not the original file.

Check your recall

During an experiment, labels = ["cat", "dog"]. What pairs does enumerate(labels, start=1) produce?

Check your answer

It produces (1, "cat") and (2, "dog").

Sources and credits

Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.