Is using range() in for loops really Pythonic?

Ben Finney bignose+hates-spam at benfinney.id.au
Mon May 12 02:24:23 EDT 2008


Ivan Illarionov <ivan.illarionov at gmail.com> writes:

> >> In such cases, the name 'dummy' is conventionally bound to the items
> >> from the iterator, for clarity of purpose
> [..]
> > If a value isn't used, then I think the most clear name for it is
> > "unused".
> [...]
> 
> Maybe my brain works differently, but I find both "dummy" and
> "unused" are extremely confusing names for loop counters. The loop
> begins to look like it doesn't iterate at all if its counter is
> dummy or unused.
> 
> If it *counts* it is *used* and it's *not* dummy.

The value is unused by any of the code inside the block. For the
purposes of that block, it is a dummy value.

That something *else* (the iterator driving the 'for') is taking care
of knowing when the loop is finished is great. However, in the code
the programmer is writing, the loop counter is entirely unused.

> Why reinvent the wheel when "a common identifier naming convention
> is for the loop counter to use the variable names i, j and k (and so
> on if needed)" (from Wikipedia
> http://en.wikipedia.org/wiki/Loop_counter )

That is also regrettably common in Python code. It still suffers from
being unnecessarily ambiguous, since there are *also* plenty of loops
using 'i', 'j', etc. where the loop counter *is* used.

Differentiating these use cases by appropriate naming is, IMO, worth
the effort of choosing a meaningful name.

-- 
 \              "Ignorance more frequently begets confidence than does |
  `\           knowledge." —Charles Darwin, _The Descent of Man_, 1871 |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list