How to Create a Line-Numbered Generator with enumerate start in Python
This Python code defines a generator that yields lines prefixed with their index, using enumerate's start parameter to offset numbering.
Python code
9 linesdef line_numbered_lines(lines, start=1):
for idx, line in enumerate(lines, start):
yield f"{idx:3} {line}"
if __name__ == "__main__":
sample = ["first line", "second", "third"]
for numbered in line_numbered_lines(sample, start=10):
print(numbered)
Output
10 first line
11 second
12 third
How it works
The enumerate built-in returns pairs of an index and an element from an iterable. Passing start=10 makes the index begin at 10 instead of 0. The generator yields formatted strings with f"{idx:3} {line}", which right-aligns the index in a 3-character field. Using a generator means each line is produced lazily, so it works with large or infinite iterables without loading them into memory.
Common mistakes
- Forgetting to pass `start` if you want numbering to start at 1; default is 0.
- Using `yield` inside a regular function without the `yield` statement, causing the function to return a generator object unexpectedly.
- Assuming enumeration works only on lists — it works on any iterable such as files or generators.
Variations
- Use a generator expression with `enumerate` and `map` to produce the formatted lines: `(f"{i:3} {line}" for i, line in enumerate(lines, 1))`
- Return a list comprehension if you need all lines at once, but be cautious with memory for large inputs.
Real-world use cases
- Adding line numbers to error messages when linting or compiling source code, aiding developers in locating issues.
- Printing numbered steps in a CLI tool for a checklist or setup wizard.
- Generating formatted numbered lists for markdown reports or documentation from a loop of items.
Sponsored
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.