Is using range() in for loops really Pythonic?

Terry Reedy tjreedy at udel.edu
Tue May 13 03:11:30 EDT 2008


"John Salerno" <johnjsal at NOSPAMgmail.com> wrote in message 
news:482912b7$0$11641$607ed4bc at cv.net...
| 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.

I believe the specific context was to counteract some people's tendency to 
write
  for i in range(len(seq)): do stuff with seq[i]
when they would better (more Pythonically) write
  for item in seq: do stuff with item
or even
  for i,item in enumerate(seq): do stuff with i and item.

One subtle but real advantage is that the latter two forms work with 
iterables that do not have a known-ahead length or which even continue 
indefinitely.

| 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.

That is an important insight.  But to me it does not negate the "do 
something n times" usage when there is no iterable other than range to 
iterate.  Do note that range has *not* been removed from 3.0 and that its 
main intended usage is for looping.

| 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.

Yes.  Python leans toward minimalism.  Proposals for various 
special-purpose loopin constructs have been rejected.  For-loops cover most 
looping needs; while-loops cover everything else.

Terry Jan Reedy






More information about the Python-list mailing list