using range() in for loops

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Wed Apr 5 08:32:58 EDT 2006


John Salerno schreef:
> I'm reading Text Processing in Python right now and I came across a 
> comment that is helping me to see for loops in a new light. I think 
> because I'm used to the C-style for loop where you create a counter 
> within the loop declaration, for loops have always seemed to me to be 
> about doing something a certain number of times, and not about iterating 
> over an object.
> 
> 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?
> 
> 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? Using for and range together seems to be a common idiom, 
> yet at the same time discouraged, so I'm wondering what is a good balance.

I felt more or less the same when I first learned Python; I was also 
used to C-style loops, coming from a C/C++ background. In the end 
though, it turned out to be a non-issue for me.

In many cases loops really are for iterating over sequences; more so 
than I realized when using for loops in C or C++. In these cases, 
Python's for statement works better than C-style loops. And if you 
really need to do something a certain number of times, there's still 
range() or xrange() to do it.

It's quite simple, I think:
- You have a sequence or iterator to loop over? Use for x in sequence.
- You want something done a set number of times? Use for i in range().
- You want to loop over a sequence and also need the index? Use for i, x 
in enumerate(sequence).

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

Roel Schroeven



More information about the Python-list mailing list