Is using range() in for loops really Pythonic?

Paddy paddy3118 at googlemail.com
Mon May 12 02:27:23 EDT 2008


On May 11, 9:28 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
Hi John, Arnaud;

> Contrived example:
>
> # Print 'hello' 10 times; x is not used
> for x in xrange(10):
>     print 'hello'

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.

I would also just use range for small, (especially small constant),
ranges.

>
> # By changing what is iterated over, no unused variable:
> from itertools import repeat
> for msg in repeat('hello', 10):
>     print msg
I guess I would not go to the trouble of using itertools.repeat unless
it was simplifying/homogenising a larger expression - i.e if it was
part of some functional expression

I've never fealt the need for a separate repeat statement myself
either.

- Paddy.

P.S: I do understand that your examples are contrived. Just my
thoughts.




More information about the Python-list mailing list