Is using range() in for loops really Pythonic?

Jonathsn Cronin jtc at theworld.com
Sun May 11 20:43:08 EDT 2008


On Sun, 11 May 2008 16:16:53 -0400, John Salerno wrote
(in message <48275446$0$11628$607ed4bc at cv.net>):

> XLiIV wrote:
> 
>> The range() function returns a list and list is a sequence, isn't?
> 
> I think you're missing the point. To me, there seems to be a fundamental 
> difference between these two things:
> 
> ---
> 
> people = ['Sam', 'Bob', 'Fred']
> 
> for name in people:
>      print name
> 
> ---
> 
> AND
> 
> ---
> 
> num = 33
> 
> for x in xrange(10):
>      print num += 1
> 
> ---
> 
> To me, the first example is a pure use of the for loop. You are 
> iterating through an object and *using* the items you are stepping through.
> 
> The second example, however, is simply doing something 10 times, and 
> what it's doing has nothing to do with 'x' or xrange. So it seems like 
> an abuse of the for loop.

I agree in principle; the first is iteration and the second is repetition.
In Python, the common idiom for a fixed number of repetitions is iterating 
over a number range.  This is true in most languages I am familiar with, 
probably because fixed repetition, where you don't care about the "index" 
value, is rarely used.

The only language I've used that does have fixed repetition is an (old) 
dialect of lisp, and I'm not sure it even made it into Common Lisp.  
Smalltalk and Ruby do have fixed repetition.

Using range may not be entirely elegant, but is pragmatic, and not, to me, 
particularly ugly.  In Python, unlike some languages, you don't have to 
declare the x.

I think you could add it without too much change to the parsing.

for <expression>:
  <block>

Seeing a ":" instead of "in" would mean a repetition statement which would
be interpreted as:
-- if <expression> evaluates to an integer, execute the block that number of 
times.
-- If <expression> evaluates to an iterator, execute the block until the 
iterator is exhausted.

Even if possible, I see this at best a minor improvement and more likely a 
negative because the for keyword is now overloaded. (see "static" in C/Java.) 
You could add a new keyword but the benefit here is much to small to justify 
the trouble.

Jonathan




More information about the Python-list mailing list