Paul Calnan
Published August 2, 2013

Someone posted to Twitter a link to a presentation on Python iteration. In it, I saw something clever.

When iterating over a file line-by-line, you generally do something like this:

with open(some_filename, 'r') as fh:
    for line in fh:
        do_something_interesting(line)

Occasionally, you need a line number associated with each line of data. I usually wind up doing something like this:

with open(some_filename, 'r') as fh:
    lineno = 0
    for line in fh:
        lineno += 1
        do_something_interesting(line, lineno)

From the presentation, I learned that you can do the same with the enumerate function:

with open(some_filename, 'r') as fh:
    for lineno, line in enumerate(fh, start=1):
        do_something_interesting(line, lineno)

I can't believe that never occurred to me before.