Is using range() in for loops really Pythonic?

Ben Finney bignose+hates-spam at benfinney.id.au
Sun May 11 18:44:19 EDT 2008


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.

> The [above] example [...] is simply doing something 10 times, and
> what it's doing has nothing to do with 'x' or xrange. So it seems
> like an abuse of the for loop.

In such cases, the name 'dummy' is conventionally bound to the items
from the iterator, for clarity of purpose::

    for dummy in range(10):
        # do stuff that makes no reference to 'dummy'

Also note that 'range' will return an iterator (not a list) in Python
3.0, and 'xrange' is removed since it's then obsolete
<URL:http://www.python.org/dev/peps/pep-3100/#built-in-namespace>.

-- 
 \          “Isn’t it enough to see that a garden is beautiful without |
  `\      having to believe that there are fairies at the bottom of it |
_o__)                                             too?” —Douglas Adams |
Ben Finney



More information about the Python-list mailing list