Is using range() in for loops really Pythonic?
Ben Finney
bignose+hates-spam at benfinney.id.au
Mon May 12 01:20:29 EDT 2008
John Salerno <johnjsal at NOSPAMgmail.com> writes:
> Ben Finney wrote:
>
> > John Salerno <johnjsal at gmailNOSPAM.com> writes:
> >
> >> num = 33
> >>
> >> for x in xrange(10):
> >> print num += 1
> >
> > Which is better done by 'num += 10'.
> >
> > Can you come up with an example that isn't trivially replaced with
> > clearer code? That might make it clearer what your concern is.
>
> ::sigh:: No, unfortunately I don't have a strong enough grasp of
> Python to give a really in-depth example.
It need not be in-depth, merely illustrative of the problem being
addressed.
> I understand what you're asking though. Perhaps people don't use
> this idiom as much as I think they do, so to give a trivial example
> to support my point isn't helpful.
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?
> As far as I know, though, I think this is used often enough, so I
> thought I'd just ask if there are purists out there who don't like
> this use of the loop and feel it's an abuse of the syntax.
No, it seems quite a normal usage of the syntax and a good use of an
iterator.
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.
--
\ "My house is on the median strip of a highway. You don't really |
`\ notice, except I have to leave the driveway doing 60 MPH." -- |
_o__) Steven Wright |
Ben Finney
More information about the Python-list
mailing list