Keeping the Index While Iterating

An enumerated loop provides a position and an item together when both are needed for the same operation.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
2 min
In this article4 chapters
  1. Choose the position's meaning
  2. Trace a filtered result
  3. Keep the source position when reporting an error
  4. Translate the position only at the display boundary

Choose the position's meaning

Enumerating names Ada and Bo in Python gives positions 0 and 1 by default. Starting at one yields 1 and 2 for a report. Zero-based indexing still identifies the true list offsets.

Trace a filtered result

Filtering out Ada before enumerating gives Bo position zero. Enumerating first and skipping Ada preserves Bo's source position one. This distinction matters when reporting the line where an invalid row appeared. Use an input boundary to define whether numbers identify the source or the filtered output.[1]

Keep the source position when reporting an error

A parser receives a first line with a valid station, a blank line, and a third line with an invalid count. Enumerating before filtering the blank makes the diagnostic refer to line three. Filtering first makes that bad record the second retained input. Both positions have a meaning. The first helps the user locate the original text, while the second could locate it in an already filtered series. Choose which one gets returned as part of the reader's result.

Translate the position only at the display boundary

A zero-based array index can support direct lookup. A printed line number can start at one. If enumeration itself starts at one, don't use the result as a list offset without translating it. In a test, place an invalid record directly after an ignored row so both expected positions visibly differ.

The same idea applies when selecting a first match. Preserve the original index through a transformation if the result points back into the input. If that input can be reordered later, a stable identifier may be needed instead of an offset. See stable identifiers for distinguishing an item's identity from its current position.

References

  1. Python Software Foundation, Python Tutorial: Control Flow ↩