brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's enumerate(start=1) numbers lines the way humans count

Python
~/tips/tip-python-enumerate-start

for n, line in enumerate(f, start=1):

Number items from 1 in a loop without adding one everywhere.

Most people know enumerate. Fewer know it takes a start argument, and that’s the bit I find most useful.

with open("config.yaml", encoding="utf-8") as f:
    for n, line in enumerate(f, start=1):
        if "\t" in line:
            print(f"line {n}: tab found")

Editors, grep -n and error messages all count lines from 1. With start=1 the numbers your script prints match what you see when you open the file, so there’s no i + 1 scattered through the f-strings and no off by one when you jump to the line.

It’s just as handy for numbered menus in a small command line script, where option 0 looks odd to anyone who isn’t a programmer.

Keep in mind that start only changes the number it hands you. It doesn’t skip anything. If you want to skip a header line, that’s a different job: call next(f) before the loop, or use itertools.islice. And if you use the number as an index back into the same list, you’re now one off, so in that case leave start at its default of 0.

Further reading: enumerate()

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link