Is using range() in for loops really Pythonic?

Ben Finney bignose+hates-spam at benfinney.id.au
Mon May 12 03:40:06 EDT 2008


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

> On Mon, 12 May 2008 16:24:23 +1000, Ben Finney wrote:
> [...]
> > 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.
> 
> Even if the counter is not used inside the loop's body it's still in
> control of the whole loop

Not in Python it's not. The values that come out of the iterator
aren't "in control of the loop". The state for the loop is in the
*iterator*, not the values that come out.

Having access to the values that come from the iterator is usually
useful, but regardless of whether one uses them or not, they're *not*
controlling the loop, and it's confusing to imply that they are.

So, when not using the values that come from the controlling iterator,
it's good to make that explicit. If Python supported it, we might
prefer to use no name at all for something that isn't used, but the
'for' syntax doesn't allow that.

In the absence of supporting syntax, the next best thing is to choose
a name that *does* make it explicit that the values will not be used.

-- 
 \         “All television is educational television. The question is: |
  `\                           what is it teaching?” —Nicholas Johnson |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list