Is using range() in for loops really Pythonic?

Grant Edwards grante at visi.com
Mon May 12 10:44:58 EDT 2008


On 2008-05-12, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote:

I too, agree that requiring a name be bound to the values
coming out of the iterator seems "wrong".

> With "do something N times", there must be *something* to keep track
> of which iteration we're up to (or, equivalently, how many iterations
> remain) at a given moment. A Python iterator seems a fine choice to
> hold that information, and better than many alternatives.

An iterator like xrange() is an excellent choice. But, since
the iterator contains that information, why require that that
value be "exported" by the iterator and bound to an externally
visible name?  In the case in question, the only thing you need
from the iterator is the StopIteration exception.  To me,
exposing the internal state of the iterator and requiring that
the user bind a name to it each time through the loop feels
we're like driving a nail with a screwdriver.

-- 
Grant Edwards                   grante             Yow! Was my SOY LOAF left
                                  at               out in th'RAIN?  It tastes
                               visi.com            REAL GOOD!!



More information about the Python-list mailing list