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.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

9 lines
Python 3.9+
def 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

stdout
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

  1. Use a generator expression with `enumerate` and `map` to produce the formatted lines: `(f"{i:3} {line}" for i, line in enumerate(lines, 1))`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.