Is using range() in for loops really Pythonic?

John Salerno johnjsal at NOSPAMgmail.com
Tue May 13 00:01:59 EDT 2008


Ben Finney wrote:

> I think that the idiom
>
>     for unused in xrange(10):
>         # do stuff with no reference to 'unused'
>
> is quite common. Is that what you're asking about?

Yes. I was more or less asking about the specific situation of using a
for loop to do something X number of times, but I think the more
generalized problem that everyone is talking about -- using a counter
variable that is never referenced in the loop -- probably puts the point
I was trying to make in a better light.

The reason I even brought this up is because I remember someone saying a
while back (probably here on the newsgroup) that the true use of a for
loop was to iterate through a sequence (for the purpose of using that
sequence), not to do something X number of times. Once they made this
comment, I suddenly saw the for loop in a new (and I believe purer)
light. That was the first time I realized what it was really meant
to do.

Using something like:

for unused in xrange(10):
    # do stuff 10 times

suddenly seemed to me like a hackish way to replace

for (int i=0; i<10; i++) {
    // do stuff 10 times;
}

Not that I think the above code (C#) looks all that elegant either. But
in C# there is a distinction between the above, and this:

foreach (int i in sequence)
    // do something;

which is more closely related to the Python for loop.

Now, you could easily make the argument that the Python for loop is a
much simpler tool to accomplish *both* of the above, and I suppose that
makes sense. Seems a little silly to have two separate for loops to do
these things. I just wasn't sure if the "counter" version of the Python
for loop was considered slightly unpythonic.



More information about the Python-list mailing list