Is using range() in for loops really Pythonic?

Paddy paddy3118 at googlemail.com
Mon May 12 11:15:49 EDT 2008


On May 12, 3:46 pm, Grant Edwards <gra... at visi.com> wrote:
> On 2008-05-12, Ben Finney <bignose+hates-s... at benfinney.id.au> wrote:
>
> > Paddy <paddy3... at googlemail.com> writes:
>
> >> I've used Fortran and C and so would tend to use either i,j,k as the
> >> unused loop variable above, or, for clarity, call it something
> >> descriptive like loop_count, if the loop body would be clearer.
>
> > The problem with all of these names is that they also have long
> > precedent as names of values that *will* be used inside the loop.
>
> I guess people who standardize on loop_count never nest loops. :)
>
> > Because of the precedent of those names, choosing one of those
> > names doesn't make it clear to the reader that the value is
> > never used; they have no indication from you of that until
> > they look over the code a few times. It's implicit rather than
> > explicit.
>
> And when somebody adds a nested loop things fall apart.
I don't have an example to hand. A lot of casses of repeat_X_times
inside a loop of repeat_Y_times would naturally be written as
repeat_Y*X_times.
Oh, wait a bit,
<oversimplified_example_alert>
for i in range(3):
  print "Stay!"
  for j in range(2):
    print "Come over."
</oversimplified_example_alert>

Which could become:

for outer_stay_repetions in range(3):
  print "Stay!"
  for inner_come_over_repetions in range(2):
    print "Come over."

But the second is daft. Nested repeats don't neccessarily pose a
problem to choosing meaningful names for repeat counters that are not
going to be referenced in the loop body, and most times i,j,k are fine
for used and un-used loop indices I find.

- Paddy
(Or were you just having a laugh ;-)



More information about the Python-list mailing list