using range() in for loops

Ben Sizer kylotan at gmail.com
Wed Apr 5 04:26:27 EDT 2006


John Salerno wrote:
> The reason for this distinction comes from the fact that I read a lot
> how using range and for is somewhat discouraged, because it doesn't
> really use a for loop for it's true purpose. So my question is, is this
> just a Python-oriented opinion about for loops, or is it a general idea?

The use of range in for loops is not discouraged, just the unnecessary
use of it. In many languages, you were forced to use range - or size,
or length, or count, etc - because the only practical method of
iteration was to use successive indices into the array or other
collection, stopping when the indexes run out. Most loops operate on
some sort of structure in this way.

In Python, you can iterate directly over the structure instead, so you
no longer have to worry about keeping track of the current index,
comparing it to the maximum index, or collecting the right object from
the structure according to its index. Python just gives you the next
object until there are none left. As a result, for most looping tasks,
you have no need to use range or an equivalent.

> Also, what if you *do* need to just do something a set number of times.
> Is this okay, or does it mean you are approaching the problem
> incorrectly?

Do you really need to do something "a number of times"? If so, range
(or xrange) is perfect for the job. More often though, you need to do
something "once for every <whatever>", so put your 'whatevers' in a
list and iterate over that.

-- 
Ben Sizer




More information about the Python-list mailing list