Is using range() in for loops really Pythonic?

Arnaud Delobelle arnodel at googlemail.com
Sun May 11 16:28:15 EDT 2008


John Salerno <johnjsal at gmailNOSPAM.com> writes:

> John Salerno wrote:
>> I know it's popular and very handy, but I'm curious if there are purists
>> out there who think that using something like:
>>
>> for x in range(10):
>>     #do something 10 times
>>
>> is unPythonic. The reason I ask is because the structure of the for loop
>> seems to be for iterating through a sequence. It seems somewhat
>> artificial to use the for loop to do something a certain number of
>> times, like above.
>>
>> Anyone out there refuse to use it this way, or is it just impossible to
>> avoid?
>
> Ok, I think most people are misunderstanding my question a little. I
> probably should have said xrange instead of range, but the point of my
> question remains the same:
>
> Should a for loop be used simply to do something X number of times, or
> should it strictly be used to step through an iterable object for the
> purpose of processing the items in that object?

It makes me feel slightly uncomfortable too, but AFAIK there is no
better way in Python.  What I sometimes do is make the for loop bind
its variable to something useful instead of an unused counter.
Contrived example:

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

# By changing what is iterated over, no unused variable:
from itertools import repeat
for msg in repeat('hello', 10):
    print msg

-- 
Arnaud



More information about the Python-list mailing list