Attach positions to values with enumerate
Attach positions to values with enumerate
enumerate produces an index and a value together while it walks an iterable. Supplying start=1 makes the index a human-facing position: the first item is position 1 instead of Python's usual zero-based sequence index. numbered_steps formats those pairs into stable labels without manually maintaining a counter.
For the three input steps, enumerate(steps, start=1) yields (1, "parse"), (2, "validate"), and (3, "store"). The function turns them into strings, and the assertion checks the exact numbering and source order. This is safer than incrementing a separate variable inside the loop because the position is bound directly to each value emitted by the iterator.
The start argument changes only the counter, not the input or its indexing rules. Choose start=0 when a label must match a list subscript, or another number when a protocol defines one. enumerate cannot supply meaningful positions for an unordered source such as a set, because that source does not promise a stable iteration order. It also does not expose an item’s original location after filtering: positions count items that reach enumerate, so enumerate before filtering if original sequence positions are required.
AI assistance was used to draft this article.
def numbered_steps(steps):
return [f"{position}. {step}" for position, step in enumerate(steps, start=1)]
steps = ["parse", "validate", "store"]
labels = numbered_steps(steps)
assert labels == ["1. parse", "2. validate", "3. store"]
print("labels:", labels)
Expected stdout:
labels: ['1. parse', '2. validate', '3. store']
Source: Python documentation: enumerate
Comments
Post a Comment