Is using range() in for loops really Pythonic?

Ivan Illarionov ivan.illarionov at gmail.com
Mon May 12 06:04:17 EDT 2008


>> 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.

I agree that "in control" was incorrect phrase.
 
> 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.

Name 'i' does not imply whether it's used inside the loop or not.
IMO it perfectly covers both cases.

It may have small advantage to "make it explicit that the values will not 
be used", but names like "dummy", "unused", "ignored" or "junk" can be 
confusing for some people and break the established conventions for 
counter variable names (and these conventions are reasonable and are 
taken from mathematics). "i" is still the best choice.

And let's agree to disagree. It's clear that we have different opinions 
and it looks that this discussion is not going to change them.

-- Ivan



More information about the Python-list mailing list